What switch cases do
Switch cases run one block of code out of several, based on the exact value of one variable. Each case is a constant that the value is compared with, and the program jumps straight to the matching one. They suit a variable that can hold a few known values, such as a menu choice, a status code or an enum value, where each value needs its own action.
Common uses
- Menus and commands. A number or letter that a user types picks an action, such as opening a file, saving or quitting.
- Status codes and states. A program can track a state, like
Idle,RunningorDone, and do something different for each one. - Enum values. Each enumerator gets its own case, and compiler warnings can point out one that is missing. The enum example in c shows how enums are declared.
- Grouped values. Several case labels with no code between them can share one action.
- Single characters. A
charis an integer type, so a switch can map letters or symbols to actions.
A menu example
#include <iostream>
int main() {
int choice = 2;
switch (choice) {
case 1:
std::cout << "Starting a new game\n";
break;
case 2:
std::cout << "Loading a saved game\n";
break;
case 3:
std::cout << "Opening the settings\n";
break;
default:
std::cout << "Unknown option\n";
break;
}
return 0;
}
With choice set to 2, the program prints Loading a saved game. The default block catches any number that has no matching case, so the program can respond to bad input instead of doing nothing. Each case ends with a break, which stops the program from running the next case too. The break statement in c covers that in more detail.
Switch cases or if else?
The same menu could be written with if and else if checks. The switch is easier to read here, because every option sits side by side under one variable. A chain of checks is the better choice when the conditions are ranges or combinations, as the if else statement syntax in c shows, or when you need to compare strings.
What switch cases can’t do
- They match exact values only. A label such as
case x > 10:will not compile. - The value must be an integer type or an enum. A
std::stringor adoublewill not work. - Each case label must be a constant that is known at compile time, so you cannot compare against a variable.
Where to go next
For the full syntax, the rules for break and fall-through, and the C++17 form, see the switch case statement in c.