Function Pointers & Callbacks
Prerequisites: Level 2 — Intermediate
A function's name, like an array's, decays into a pointer to it — letting a function be stored in a variable, passed as an argument, or chosen at runtime.
int add(int a, int b) { return a + b; }
int subtract(int a, int b) { return a - b; }
int compute(int a, int b, int (*operation)(int, int)) {
return operation(a, b);
}
int main(void) {
printf("%d\n", compute(5, 3, add)); // 8
printf("%d\n", compute(5, 3, subtract)); // 2
return 0;
}
This is exactly how qsort (from <stdlib.h>) accepts a custom
comparison function, and how C code implements what other languages
call a callback, without any special language feature beyond
ordinary pointers.
Common mistakes
- Mismatching a function pointer's declared signature with the actual function assigned to it — the types must match exactly, including parameter and return types.