pointers-memory · intermediate · ~15 min

Opcode dispatcher using function pointer table

Index and invoke function pointers safely from a jump table with bounds verification.

Challenge

Virtual machines, emulator decoders, and command interpreters use function pointer jump tables instead of large switch statements to achieve $O(1)$ dispatch.

Your Task

Implement:

typedef int (*opcode_handler_t)(int a, int b);

int dispatch_opcode(uint8_t opcode, int a, int b, opcode_handler_t *table, size_t table_len);

Rules

  1. If table == NULL, return -999999.
  2. If opcode >= table_len, return -999999 (invalid opcode).
  3. If table[opcode] == NULL, return -999999 (unimplemented opcode).
  4. Otherwise, execute table[opcode](a, b) and return its result.

Example

opcode_handler_t ops[4] = { add, sub, mul, NULL };
dispatch_opcode(0, 10, 5, ops, 4); // returns 15 (add)
dispatch_opcode(3, 10, 5, ops, 4); // returns -999999 (NULL handler)
dispatch_opcode(5, 10, 5, ops, 4); // returns -999999 (out of bounds)

Input format

opcode: byte index; a, b: integer operands; table: array of function pointers; table_len: table size.

Output format

Returns handler result or -999999 on error.

Constraints

C11 freestanding. Safe function pointer invocation.

Starter code

#include <stdint.h>
#include <stddef.h>

typedef int (*opcode_handler_t)(int a, int b);

/* Execute table[opcode](a, b). If opcode is out of bounds, table is NULL,
   or handler is NULL, return -999999. */
int dispatch_opcode(uint8_t opcode, int a, int b, opcode_handler_t *table, size_t table_len) {
    (void)opcode; (void)a; (void)b; (void)table; (void)table_len;
    return -999999;
}

Common mistakes

Invoking table[opcode] without checking for NULL; off-by-one check on table_len.

Edge cases to handle

opcode >= table_len; table[opcode] == NULL; table == NULL; valid handler returning negative.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.