The switch statement β branching by integer value. case, break, default and fallthrough.
switch (x) { case 1: ... break; default: ...; } formbreak; at the end of each casedefault runs when no case matchesbreak)case labels must be constant expressionselse if is just an extension of if/else, so it belongs there. This page focuses on the switch statement β a different construct that dispatches on an integer value.
int day = 3; switch (day) { case 1: printf("Monday\n"); break; case 2: printf("Tuesday\n"); break; case 3: printf("Wednesday\n"); break; default: printf("Unknown\n"); }
break; execution "falls through" into the next case and keeps running — a common source of bugs.switch (n) { case 1: printf("A\n"); // no break! case 2: printf("B\n"); // no break! case 3: printf("C\n"); break; } // When n=1: prints A, B, and C!
breakday 1–3, but you forgot every single break:
int day = 1; switch(day){ case 1: printf("Mon\n"); // no break case 2: printf("Tue\n"); // no break case 3: printf("Wed\n"); // no break default: printf("Unknown\n"); }
Mon
Tue
Wed
Unknowncase 1; instead of case 1:?: and semicolon ; sit next to each other on the keyboard, so this typo happens often.
switch(day){ case 1; // β typed ; instead of : printf("Mon\n"); break; }
error: expected ':' or '...' before ';' token: after case 1 to form a label.
: after case marks a label (same syntax as goto labels). Statements end with ;; labels end with :.
default; instead of default:default is also a label. default; may compile (as an empty statement) but it becomes a silent bug: the "no case matched" branch never runs.
case 1: case 2: printf("small\n"); break; // intentional
default for unmatched casesbreak deliberately to see fall-through'a') in casecase 1: case 2:)Check your understanding of this lesson!
Without break, execution continues into every case that follows the matched one. This is called "fallthrough".
default is optional, but it's usually recommended because it lets you handle the case when nothing matches.
switch supports integer types (int, char, etc.) only. float and double cannot be used.
Combine this interactive site with books for more practice.
* Links above are affiliate links. Purchases help support this site.