What a switch statement does
A switch statement compares one value against a list of constant labels. It jumps to the label that matches and runs from there, stopping at a break or at the end of the switch. In C and C++, the value must be an integer type or an enum. A switch is a common way to handle a menu choice, a status code or a command letter.
The parts of a switch
switch (value) { // the value to test
case 1: // a constant label
// statements for this label
break; // stop here
case 2:
// statements for this label
break;
default: // runs when no label matches
// statements for everything else
break;
}
The value is tested once. Each label must be a constant that the compiler knows when it builds the program, such as a number, a character or an enum constant. The default label is optional.
How execution moves through a switch
- The value in the parentheses is evaluated.
- The program jumps to the case label with the same value. If no label matches and there is a
default, it jumps there. If no label matches and there is nodefault, nothing inside the switch runs. - Statements run from that label downward until a
break, the end of the switch, or another statement that leaves it.
The break statement in C is what keeps each branch separate. Without it, the next case runs as well.
Switch compared with if else
Here is the same logic written both ways, for a variable day that holds 1 or 2:
// with a switch
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
default:
printf("Another day\n");
break;
}
// with an if else chain
if (day == 1) {
printf("Monday\n");
} else if (day == 2) {
printf("Tuesday\n");
} else {
printf("Another day\n");
}
Both do the same job here. A switch tends to read more clearly when many branches test the same variable against fixed values. An if else chain fits better when each test is different, such as a comparison between two variables. For those cases, the if else statement syntax in C is the right tool.
When a switch fits and when it does not
A switch works well for:
- one integer, character or enum value tested against several fixed options
- a menu, a command code or a status code with a known set of values
A switch does not work for:
- floating-point values, since a switch only handles integer types
- strings. In C, compare text with
strcmp(). In C++, use anifchain or a lookup, becausestd::stringis not an integer type - ranges, such as every score from 50 to 59. Each case label is a single value. Some compilers offer a range extension, but it is not standard C or C++
- labels that are only known while the program runs. Case labels must be constants
Summary
A switch statement picks one block by matching a single integer or enum value against constant case labels. It suits many fixed options on one variable. For ranges, text or conditions that involve several variables, an if else chain is usually the better choice.