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 now covered in Lesson 8 (if statement). Chaining else if is really just an extension of if/else, so it belongs there. This page focuses on switch β 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"); }
int, char, and so on). You can't switch on doubles or strings.break;, execution "falls through" into the next case and keeps running — a classic 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 comes up all the time.
switch(day){ case 1; // β typed ; instead of : printf("Mon\n"); break; }
error: expected ':' or '...' before ';' token: after case 1 to complete the label.
: after case marks a label (same syntax as goto labels). Statements end with ;; labels end with :.
default; instead of default:default is a label too. default; may compile (as an empty statement), but it becomes a silent bug β the "no case matched" branch never runs.
break on purpose. Add a comment so reviewers know it's deliberate:case 1: case 2: printf("small\n"); break; // intentional
default to catch unmatched valuesbreak on purpose to see fall-through'a') in case labelscase 1: case 2:)Check your understanding of this lesson!
Without break, execution keeps running into every case that follows the matched one. This is called "fallthrough."
default is optional, but it's usually worth including so you have somewhere to handle unmatched values.
switch only accepts integer types (int, char, and so on). float and double aren't allowed.