Basics
suggest changeJust like you can have a pointer to an int, char, float, array/string, struct, etc. - you can have a pointer to a function.
Declaring the pointer takes the return value of the function, the name of the function, and the type of arguments/parameters it receives.
Say you have the following function definition:
int addInt(int n, int m){
return n+m;
}
You can declare and initialize a pointer to this function:
int (*functionPtrAdd)(int, int) = addInt; // or &addInt - the & is optional
If you have a void function it could look like this:
void Print(void){
printf("look ma' - no hands, only pointers!\n");
}
Then declaring the pointer to it would be:
void (*functionPtrPrint)(void) = Print;
Calling through the pointer can be written with an explicit dereference:
sum = (*functionPtrAdd)(2, 3); //will assign 5 to sum
(*functionPtrPrint)(); //will print the text in Print function
As seen in more advanced examples in this document, declaring a pointer to a function could get messy if the function is passed more than a few parameters. If you have a few pointers to functions that have identical “structure” (same type of return value, and same type of parameters) it is best to use typedef to save typing and to make the code clearer:
#include <stdio.h>
typedef int (*ptrInt)(int, int);
int Add(int i, int j){
return i+j;
}
int Multiply(int i, int j){
return i*j;
}
int main(void)
{
ptrInt ptr1 = Add;
ptrInt ptr2 = Multiply;
printf("%d\n", (*ptr1)(2,3)); //will print 5
printf("%d\n", (*ptr2)(2,3)); //will print 6
return 0;
}
You can also create an Array of function-pointers. If all the pointers are of the same “structure”:
int (*array[2]) (int x, int y); // can hold 2 function pointers
array[0] = Add;
array[1] = Multiply;
You can learn more here and here.
It is also possible to define an array of function pointers of different types, though that requires a cast whenever you call a specific function. The call is undefined behavior if the function's type is not compatible with the type used for the call. You can learn more here.