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
- A
typedef enumgives the type one short name. - Listing every case lets the compiler warn about a missing one.
- A count member last sizes arrays by the enum.
Keywords and builtins used here
casecharconstdefaultenumreturnstate_nameswitchtypedef
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.
Step 6 of 7 in Operators & flow, step 13 of 35 in Language basics.