Simvik

Table-driven state machine

Look up a transition in a table, run its action and return the next state. A medium embedded C problem (State machines), run and graded in the browser.

medium · State machines · fsm · tables · function-pointers

A transition table keeps a state machine's behaviour in data. Find the first row whose state matches the current state (or is ANY_STATE) and whose event matches the event. Call its action if it has one, and return its next state.

If no row matches, the event is ignored: call nothing and return the current state. Rows are checked in order, so an earlier row overrides a later ANY_STATE row.

Starter code

uint8_t fsm_dispatch(const transition_t *table, size_t n, uint8_t state, uint8_t event) {
  for (size_t i = 0; i < n; i++)
    if (table[i].state == state && table[i].event == event)
      return table[i].next;
  return state;
}

Example tests

Transitions with actions

step(IDLE, START);
step(RUNNING, FINISH);

Expected output:

beep 1
beep 2

An event with no row is ignored

step(IDLE, FINISH);

Expected output:

0

Learn it first

More State machines problems