To define a function pointer, use the following syntax:
return_type (*ref_name) (type args, ...)
So, to define a reference to a function called "doSomething" that returns an int
and takes an int
argument, you should write this:
int (*doSomething)(int number);
Then you can assign a link to the actual function as follows:
int someFunction(int argument) { printf("%i", argument); } doSomething = &someFunction;
After that, you can call it directly:
doSomething(5);
Because function pointers are essentially just pointers, you can really use them as instance variables in your classes.
When accepting function pointers as arguments, I prefer to use typedef
instead of using cluttered syntax in the function prototype:
typedef int (*FunctionAcceptingAndReturningInt)(int argument);
Then you can use this new type as the argument type for the function:
void invokeFunction(int func_argument, FunctionAcceptingAndReturningInt func) { int result = func(func_argument); printf("%i", result); } int timesFive(int arg) { return arg * 5; } invokeFunction(10, ×Five);
Jacob Relkin
source share