Function Pointers & Callbacks
The Programmable Remote Control
In most C code, you call functions by name: printf(), strlen(), main(). But what if you could store a function in a variable, pass it to another function, or pick which function to call at runtime?
That's what function pointers do. Just like a regular pointer holds the address of a variable, a function pointer holds the address of a function. It's like a remote control where each button stores the address of a different action β and you can reprogram the buttons.
The Syntax (Yes, It's Ugly)
A function pointer declaration looks like this:
return_type (*pointer_name)(param_types);
The parentheses around *pointer_name are critical. Without them, you'd be declaring a function that returns a pointer β a very different thing.
Basic Function Pointer
typedef to the Rescue
The raw syntax for function pointers is notoriously hard to read. typedef lets you create a clean, readable name for the function pointer type. Once you define the type, you can declare variables, function parameters, and arrays with it β just like any other type.
typedef for Function Pointers
Callbacks β Passing Functions as Arguments
A callback is a function you pass to another function, saying: "Call this when you need to." It's one of the most powerful patterns in C. The standard library uses it everywhere β qsort, bsearch, signal handlers, and more.
Think of it like hiring a contractor and handing them a phone number: "When the job is done, call this number." The contractor doesn't know who they're calling β they just dial the number you gave them.
Callback Pattern
Real-World Example: qsort
The C standard library's qsort function sorts any array β integers, strings, structs, anything. How? It takes a comparator callback that tells it how to compare two elements. You provide the logic; qsort provides the sorting algorithm.
The comparator must return:
- Negative if the first element should come before the second
- Zero if they're equal
- Positive if the first should come after the second
Using qsort with a Custom Comparator
Dispatch Table β Array of Function Pointers
An array of function pointers is called a dispatch table. Instead of a long switch statement, you index into an array and call the function at that position. This pattern is used in interpreters, command processors, and state machines.