C Programming Function Pointers
Last modified by Microchip on 2023/11/09 09:06
- Pointers may also be used to point to functions.
- Provides a more flexible way to call a function, by providing a choice of which function to call.
- Makes it possible to pass functions to other functions.
- Not extremely common, but very useful in the right situations.
Declaration
A function pointer is declared much like a function prototype:
1
int (*fp)(int x);
Here, we have declared a function pointer with the name fp
- The function it points to must take one int parameter
- The function it points to must return an int
Initialization
A function pointer is initialized by setting the pointer name equal to the function name.
If we declare the following:
1
2
2
int (*fp)(int x); //Function pointer
int foo(int x); //Function prototype
int foo(int x); //Function prototype
We can initialize the function pointer like this:
1
fp = foo; //fp now points to foo