c / expert
Snippet
Function Pointer Dispatch Tables
Instead of using large switch-case blocks for state machines or instruction decoding, expert C code uses dispatch tables. These are arrays of function pointers indexed by an enum or opcode. This pattern improves branch prediction, reduces cyclomatic complexity, and makes the code more extensible (O(1) lookup vs O(n) or O(log n) branching).
snippet.c
1
2
3
4
5
6
7
8
9
10
11
typedef void (*handler_t)(int);void handle_init(int v) { /* ... */ }void handle_stop(int v) { /* ... */ }handler_t dispatch[] = {[STATE_INIT] = handle_init,[STATE_STOP] = handle_stop};// Usage: dispatch[current_state](payload);
Breakdown
1
typedef void (*handler_t)(int);
Defines a type for a pointer to a function taking an int and returning void.
2
[STATE_INIT] = handle_init
Uses C99 designated initializers to map enums to specific function addresses.