Simvik

Replace a switch with a table

Select an operation by opcode using an array of function pointers. An easy embedded C problem (Function pointers and state machines), run and graded in the…

easy · Function pointers and state machines · dispatch-table

Implement a tiny calculator. opcode selects the operation applied to a and b:

  • 0: add
  • 1: subtract
  • 2: multiply
  • 3: divide (return 0 when b is 0)

Any other opcode returns 0. Use a table of function pointers indexed by the opcode instead of a switch.

Starter code

int32_t calc(uint8_t opcode, int32_t a, int32_t b) {
  // Look the operation up in a table of function pointers.
  return 0;
}

Example tests

Add and subtract

printf("%d %d\n", calc(0, 7, 3), calc(1, 7, 3));

Expected output:

10 4

Multiply and divide

printf("%d %d\n", calc(2, 7, 3), calc(3, 7, 3));

Expected output:

21 2

Learn it first

More Function pointers and state machines problems