Switch Statements
The switch statement lets you compare a single expression against multiple possible values. Depending on the matched value, it runs a different block of code.
It’s a less cluttered alternative to using long if/else if chains when you’re comparing one variable against several fixed values.
A basic switch statement
The basic syntax is
switch (expression) { case value1: // code to run if expression == value1 break; case value2: // code to run if expression == value2 break; default: // code to run if no case matches}The switch keyword is followed by an expression in parentheses. This expression is evaluated and then matched against each value listed after the case keyword, in order. If a value is matched, all code up to the next break; statement is executed.
If no case matches, the default case is executed.
Example
Here’s an example that maps a number to the name of the day:
As day holds 3, the program matches case 3:, prints Wednesday, and then stops at break; on line 15. The other cases are skipped entirely.
Key rules
- The expression must produce an integer or character value, like
int,char, orenum(you’ll meet enums later). You cannot useswitchon strings, floats, or doubles. - The
casevalues must be constants. - The
break;statement stops execution. Without it, code “falls through” to the next case. - The
defaultcase is optional, but it’s considered good practice since it catches unmatched values.
The break keyword, and why it exists
As mentioned above, if you omit break;, execution continues into the next case. This is called fall-through. Fall-through was designed to group cases, so it can be used intentionally, as in the following example:
Here, 'A' and 'B' share the same output because there’s no break between them. Likewise with 'C' and 'D'.
A pitfall: Forgetting the
breakis a common mistake. Some people make a habit of writingbreakas soon as they write thecaseline, then fill in the logic afterwards.
Using switch versus if/else if
Both let you branch on conditions, so how do you decide which to use?
Developers reach for switch when they’re comparing one variable against several known values, checking each for equality. They tend to default to if/else if when conditions involve ranges, multiple variables, or anything beyond a direct equality check, like length >= 10 or x > 0 && y > 0.
Checkpoint
What happens when this code runs?
int level = 2;
switch (level) {
case 1:
std::cout << "Beginner";
case 2:
std::cout << "Intermediate";
case 3:
std::cout << "Advanced";
break;
default:
std::cout << "Unknown";
}Which value could you legally use as a switch expression without changes?
You’re computing a shipping cost based on an order’s weight. Different price tiers are based on weight ranges like under 5kg, 5 to 20kg, and over 20kg. Which should you reach for?