0 day streak
cpp / expert
Snippet

Discrete Event Dispatching via Function Pointer Arrays

Instead of using large switch-case or if-else blocks that can lead to branch mispredictions, this technique uses a jump table (an array of function pointers). This allows for O(1) constant-time dispatching to the appropriate logic based on an index.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
enum class Action { Start, Stop, Pause, Reset, Count };
void doStart() {} void doStop() {} void doPause() {} void doReset() {}
typedef void (*Handler)();
static const Handler jumpTable[] = { doStart, doStop, doPause, doReset };
void execute(Action a) {
if (a < Action::Count) {
jumpTable[static_cast<int>(a)]();
}
}
Breakdown
1
static const Handler jumpTable[] = { ... };
Defines an immutable array of function pointers corresponding to the enum values.
2
jumpTable[static_cast<int>(a)]();
Directly jumps to the code address associated with the action, bypassing complex branching logic.