0
How can we use callbacks in ANSI-C?
I have already tried it, see here: https://code.sololearn.com/cg5LJ8X2P10Z/?ref=app But this methode doesn't worked. How I use callbacks in C?
3 ответов
+ 1
You have to use function pointers instead of regular pointers.
A function pointer is defined as follows:
function_return_type (*variable_name) ( parameter_types, ... );
Might take a bit to get used to.
This would be the corrected program:
#include <stdio.h>
// function prototype
int sum( int, int );
int main() {
printSum(2,4, sum);
return 0;
}
int sum(int a, int b){
// No need for +=
return a+b;
}
void printSum(int a, int b, int (*doSum)(int, int)){
// doSum is the function pointer name
printf("%d",doSum(a,b));
}
+ 1
@Hornetfly
The file is processed from top to bottom, assuming there is no prototype, when it reaches this line: printSum(2,4, sum);
C has to know what printSum is and what sum is.
Since the compiler hasn't come across sum yet it has no idea what that variable is. So with a prototype we tell C that sum is a function and that it exists somewhere.
But we don't have a prototype for printSum either and that still compiles? You may ask.
Well, C is a little weird.
When you call a function, C assumes the function already exists and has a int return type.
It's later the linkers job to find the correct function.
If you would output printSum's return type, you could, even though it returns void, C thinks it's an int.
So actually the correct program would also have a prototype for printSum ( which I forgot, sorry ) above main.
void printSum(int, int, int (*)(int,int));
C would give out a bunch of warnings without the prototypes.
But in C++ this wouldn't compile.
0
Dennis Thank you, that worked for me.
But why we need a function prototype?