c / expert
Snippet
Dynamic Operation Dispatch via Function Pointer Jump Table Matrix
This snippet presents a high-performance jump table matrix using C99 designated initializers with function pointers. Direct indexing into the dispatch array replaces costly conditional branching chains with O(1) constant-time function lookup.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>typedef enum {OP_ADD,OP_SUB,OP_MUL,OP_COUNT} OpCode;typedef int (*OpHandler)(int, int);static int exec_add(int a, int b) { return a + b; }static int exec_sub(int a, int b) { return a - b; }static int exec_mul(int a, int b) { return a * b; }static const OpHandler JUMP_TABLE[OP_COUNT] = {[OP_ADD] = exec_add,[OP_SUB] = exec_sub,[OP_MUL] = exec_mul};int dispatch_op(OpCode code, int operand1, int operand2) {if (code < 0 || code >= OP_COUNT) {return 0;}return JUMP_TABLE[code](operand1, operand2);}
Breakdown
1
typedef int (*OpHandler)(int, int);
Defines a clean function pointer type signature for operation handler routines.
2
[OP_ADD] = exec_add,
Uses C99 designated array initializer syntax to explicitly pair opcode enum keys with handlers.
3
if (code < 0 || code >= OP_COUNT) {
Validates boundary checks to prevent out-of-bounds array access before table dereferencing.
4
return JUMP_TABLE[code](operand1, operand2);
Executes function call dynamically via direct constant-time jump table lookup.