Loading lessons...
Function Pointers and Callbacks
Function Pointers and Callbacks
Just like variables, functions have addresses. A function pointer stores one; passing it to another function creates a callback.
Storing a function's address
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int main() {
int (*op)(int, int) = add; // op points to add
printf("%d\n", op(5, 3)); // 8
op = sub;
printf("%d\n", op(5, 3)); // 2
return 0;
}
The syntax
int (*op)(int, int) reads: a pointer to a function taking two ints and returning int.
Callbacks
Passing a function pointer into another function lets it "call back" into your code:
void apply(int (*f)(int), int x) {
printf("%d\n", f(x));
}
Real uses
- Sorting with custom comparators.
- Event handlers and menus.
- Generic library hooks.
TL;DR
- A function pointer stores a function's address.
- Declare:
int (*op)(params). - Call through it like a normal function.
- Callbacks = passing a function to another function.