switch exists because comparing one value against many fixed constants is common enough — menu dispatch, state machines, day-of-week tables, instruction decoding — that the language gives it dedicated syntax. The payoff is real: the compiler can turn a switch into a single jump-table lookup, one indexed jump instead of testing each else if in turn.
switch
When you are comparing one integer (or char) against a list of fixed values, switch reads better than a ladder of else-ifs:
int day = 3; switch (day) { case 1: std::cout << "Mon\n"; break; case 2: std::cout << "Tue\n"; break; case 3: std::cout << "Wed\n"; break; default: std::cout << "unknown\n"; break; }
Rules that matter:
- Each
casemust be a compile-time constant (a literal or const int). You cannot switch on astd::stringor on ranges. breakis mandatory at the end of each case. Without it, execution falls through into the next case's code. Occasionally useful, usually a bug.defaultruns when nothing matched, like a finalelse.
Python only recently got match. C++'s switch is older and dumber: it is a fast jump on a number, nothing more.
Code exercise · cpp
Run this and observe the fallthrough bug: case 2 has no break, so after printing Tue it falls into case 3 and prints Wed too. Then fix it by adding the missing break so the output is only `Tue`.
Worked example: fall-through as a feature
Because execution falls through until it hits a break, several case labels can deliberately share one body. This is the one situation where omitting break between cases is idiomatic rather than a bug:
char c = 'e'; switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': std::cout << "vowel\n"; break; default: std::cout << "consonant\n"; break; }
All five vowel labels funnel into the same two lines. Anything else lands on default.
Code exercise · cpp
Run the vowel classifier, then change c to 'k' in your head: which label catches it? Try editing and re-running to confirm.
Quiz
In a switch, what happens if a matching case has no break at the end?