EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 50
Function Pointers and Callbacks
Plugging behaviour in at run time.
A function pointer stores the address of a function, so code can call whichever one it was given. A button driver can accept a callback and call it when a press is detected, without knowing what the press does.
Tables of function pointers make neat command dispatchers and state machines. Always check a pointer is not null before calling it.
Interrupt vector tables are, at heart, arrays of function pointers.
EXAMPLE
typedef void (*Callback)(void);
static Callback on_press = 0;
void button_set_handler(Callback cb) { on_press = cb; }
void button_event(void) { if (on_press) on_press(); }