A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
A switch is a computed goto with syntax sugar. That is not an insult. It is literally what the compiler generates: a jump table indexed by the switch expression. Understanding this explains both why switch is fast for dense integer ranges and why fall-through exists. The cases are labels. Execution enters at the matching label and continues downward until it hits a break or the closing brace. There is no implicit boundary between cases.
#include <stdio.h>int main(void) {int day = 3;switch (day) {case 1:printf("Monday\n");break;case 2:printf("Tuesday\n");break;case 3:printf("Wednesday\n");break;case 4:printf("Thursday\n");break;case 5:printf("Friday\n");break;default:printf("Weekend or invalid\n");break;}return 0;}
Omit a break and execution falls into the next case. Sometimes this is deliberate. Grouping multiple cases that share logic is idiomatic C. But accidental fall-through is one of the most common C bugs, and compilers before C23 did not warn about it by default.
#include <stdio.h>int main(void) {int status_code = 404;switch (status_code) {case 200:printf("OK\n");break;case 403:case 404:case 410:printf("Client error: %d\n", status_code);break;case 500:case 502:case 503:printf("Server error: %d\n", status_code);break;default:printf("Unknown status: %d\n", status_code);}return 0;}
Cases 403, 404, and 410 share the same handler. No break between them means they all flow into the printf. This is clean, intentional grouping. The comment /* fall through */ is conventional when the fall-through is deliberate, so the next reader does not add a break thinking they are fixing a bug.
Compile with -Wimplicit-fallthrough (GCC 7+) or -Wimplicit-fallthrough=5 to get warnings on unintentional fall-through. In C23, the [[fallthrough]] attribute explicitly marks intentional cases and silences the warning.
The switch expression must evaluate to an integer type. No floats, no strings, no ranges (outside of GCC's non-standard case 1 ... 5 extension). If you find yourself wanting to switch on a string, you need an if-else chain or a lookup table. This limitation trips up people arriving from languages with pattern matching.
switch is the right tool for dispatching on a small set of integer constants. For everything else, if-else chains or lookup arrays serve better. Next lesson: while loops, where the condition-before-body ordering creates its own class of off-by-one headaches.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.