C Switch Statement
The switch statement is an alternative to long if/else if chains when comparing one variable against many possible constant values. Each possible value is a case label.
Without a break statement, execution falls through to the next case, which is a common source of bugs, so remember to add break at the end of each case block.
switch (expression) {
case value1:
// code
break;
default:
// code
}How switch works
The switch expression is evaluated once and compared against each case value in order. When a match is found, execution jumps there and continues until a break or the end of the switch.
The default case
The optional default case runs when no other case matches, similar to a final else in an if/else if chain.
#include <stdio.h>
int main() {
int day = 3;
switch (day) {
case 1: printf("Mon\n"); break;
case 2: printf("Tue\n"); break;
case 3: printf("Wed\n"); break;
default: printf("Unknown\n");
}
return 0;
}Wedday matches case 3, so 'Wed' is printed, and break stops fall-through.
#include <stdio.h>
int main() {
int x = 1;
switch (x) {
case 1:
case 2:
printf("One or Two\n");
break;
default:
printf("Other\n");
}
return 0;
}One or TwoGrouping case 1 and case 2 without a break between them shares one code block.
Key points
- switch compares one expression against multiple constant case values.
- break prevents fall-through into the next case.
- default runs when no case matches.
- Case values must be integer or character constants.
