switch#
 1#include <stdio.h>
 2#include <stdlib.h>
 3#include <unistd.h>
 4enum { IDLE, BREWING, DONE } state = IDLE;
 5
 6int main() {
 7  while (true) {
 8    switch (state) {
 9    case IDLE:
10      puts("Idle 💤");
11      if (getchar() == 's')
12        state = BREWING;
13      break;
14    case BREWING:
15      puts("Brewing 🌊");
16      sleep(2);
17      state = DONE;
18      break;
19    case DONE:
20      puts("DONE ☕");
21      switch (getchar()) {
22      case 'e':
23        return EXIT_SUCCESS;
24        break;
25      case 'r':
26        state = IDLE;
27      }
28    }
29  }
30}
$ echo s\ne | code-wi/switch.exe
Idle 💤
Brewing 🌊
DONE ☕
DONE ☕
In the example above we get two times DONE ☕, because the newline from the first command must be consumed first by the getchar in line 21. So the DONE state is entered twice.
Prefer switch if you have multiple individual options for a variable. Choose if-else if you have numeric ranges.
Activity 27  (State machine using switch)
You probably implemented the last activity using an if-else. Now use a switch.
