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
bis 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 4Multiply and divide
printf("%d %d\n", calc(2, 7, 3), calc(3, 7, 3));Expected output:
21 2Learn it first
- Function pointers and callbacks · Callbacks, dispatch tables and the context pointer that makes them reusable.
More Function pointers and state machines problems
- Dispatch through a vector table · Call the handler registered for an interrupt number, with a safe fallback.
- Apply a function to a buffer · Transform every element of an array with a caller-supplied function.
- Command table lookup · Find a command by name in a table and call its handler.
- Sort with a comparator · Sort an array into an order defined by a callback.
- State transition function · Implement the transition rules of a motor controller.
- Publish and subscribe · Keep a fixed-size list of callbacks and notify them in order.
- Callback with context · Invoke a callback for every set bit, passing through a user context.
- Generic minimum · Find the smallest element of an array of any type using a comparator.
- State handlers · Build a state machine in which each state is a function.
- TV remote: a table of key actions · Look a key code up in a table and call its action with the device's context.