Using C's else if and switch statements for multi-way conditional branching.
else if.int score = 75; if (score >= 90) printf("Excellent\n"); else if (score >= 70) printf("Good\n"); else if (score >= 50) printf("Pass\n"); else printf("Fail\n");
score >= 50 comes first, even 90 and 70 match there and everyone "Passes". Put the strictest condition first.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!
case 1: case 2: printf("small\n"); break;
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.