Function Pointers
Pointers to code, not data, and the declaration syntax that looks worse than it is
In a nutshell
A function pointer holds the address of a function. Declaring one requires a syntax you have not seen: int (*cmp)(const void *, const void *); reads “cmp is a pointer to a function that takes two const void * and returns int.” You assign it by writing the function name without the call parens (cmp = compare_ints;) and you call through it exactly like a regular function (int r = cmp(a, b);). The Java analogue is a lambda or functional-interface reference; the mechanical picture is “an entry point address you can pass around.”
Why it matters
Function pointers are how C does callbacks. qsort takes one. Event handlers take one. State machines use tables of them. Every C library that wants to let the caller customize behavior without rewriting the library uses function pointers at its API. They are also how C programs implement polymorphism (the Linux kernel’s VFS is a table of function pointers; so is every device driver interface).
Key takeaways
- Declaration syntax.
return_type (*name)(param_types);. The parens around*nameare required; without them it parses as a function returning a pointer. typedefmakes declarations readable.typedef int (*Comparator)(const void *, const void *);thenComparator cmp = my_compare;.- Call through is just like a regular call.
cmp(a, b)or the older-syntax(*cmp)(a, b)— both work. - Function names decay to function pointers in most expressions, similar to arrays.
cmp = strcmp;works becausestrcmpis implicitly&strcmpin that context. - Signatures must match exactly. A function pointer typed for
int(int, int)cannot holdlong foo(int, int)without an explicit cast and undefined behavior.
Lessons in this topic
| Lesson | What it covers |
|---|---|
| Function Pointers | Declaration syntax, typedef to tame it, assigning and calling, the callback pattern |
Practice and deep dives
Practice this topic: Function Pointers drill, or browse the practice gallery.
What comes next
Generic Containers & qsort — putting void * and function pointers together into libraries that work on any type.