Quiz Entry - updated: 2026.07.10
What are function pointers and why would you use them?
A function pointer holds the address of a function, so you can store, pass, and call functions by variable — the basis for callbacks and hand-rolled polymorphism.
* A struct's function-pointer field dispatches to iam_a_bike or iam_a_car at runtime — manual polymorphism, like a virtual method. *
Declaration syntax:
<return_type> (*<name>)(<param_list>);
// Example: pointer to function taking int, returning void
void (*callback)(int);
Use case: Manual polymorphism (like virtual methods)
void iam_a_bike(void) { printf("I am a bike.\n"); }
void iam_a_car(void) { printf("I am a car.\n"); }
struct vehicle {
// Function pointer member
void (*iam)(void);
int wheels;
};
void init(struct vehicle *v, int w) {
v->wheels = w;
if (w <= 2) v->iam = iam_a_bike;
else v->iam = iam_a_car;
}
void print(struct vehicle *v) {
// Calls the right function based on type!
v->iam();
printf("I have %d wheels.\n", v->wheels);
}
int main(void) {
struct vehicle v;
init(&v, 2);
// "I am a bike. I have 2 wheels."
print(&v);
}
Common uses:
- Callback functions (event handlers, signal handlers)
- Sorting with custom comparators (
qsort) - Plugin architectures
- State machines
Tip: Use https://cdecl.org/ to decode complex function pointer declarations!
Go deeper:
Function pointer — Wikipedia — function pointers, callbacks, and polymorphism in C.