Declaring Function Pointers
Pointers to functions.
Functions Have Addresses
Just like data, every function lives at an address in memory. A function pointer stores that address so you can call the function indirectly.
#include <stdio.h>
void greet(void) { printf("hello\n"); }
int main(void) {
void (*fp)(void) = greet;
fp();
return 0;
}Reading the Declaration
The declaration int (*fp)(int) means: fp is a pointer to a function taking an int and returning an int.
The parentheses around *fp are required.
#include <stdio.h>
int square(int x) { return x * x; }
int main(void) {
int (*fp)(int) = square;
printf("%d\n", fp(5));
return 0;
}All lessons in this course
- Declaring Function Pointers
- Passing Functions
- qsort with Comparators
- Function Pointer Tables