typestar

Enums as state in C

An enum names the states, and a switch over it makes the gaps visible.

typedef enum {
    STATE_IDLE,
    STATE_RUNNING,
    STATE_DONE,
    STATE_COUNT
} State;

const char *state_name(State s) {
    switch (s) {
    case STATE_IDLE:
        return "idle";
    case STATE_RUNNING:
        return "running";
    case STATE_DONE:
        return "done";
    default:
        return "unknown";
    }
}

How it works

  1. A typedef enum gives the type one short name.
  2. Listing every case lets the compiler warn about a missing one.
  3. A count member last sizes arrays by the enum.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
255
Tokens
60
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 42 seconds.

Type this snippet

Step 6 of 7 in Operators & flow, step 13 of 35 in Language basics.

← Previous Next →