Lesson 3 of 6 · Control Flow · 2 min read · Updated
switch, and why break matters
A cleaner way to pick between many fixed choices — with one famous trap.
When you are comparing one variable against several fixed values, a chain of else if gets noisy. switch says the same thing more clearly.
int day;
printf("Day number (1-7): ");
scanf("%d", &day);
switch (day) {
case 1:
printf("Monday\n");
break;
case 6:
case 7:
printf("Weekend\n");
break;
default:
printf("A weekday\n");
}
Notice that case 6 has no body. Control falls straight through into case 7, so both print "Weekend". That is deliberate here — and it is exactly what causes trouble when it is not.
Warning
Forget break and execution falls through into the next case and keeps going. A missing break is one of the most common C bugs, and the compiler will not complain.
What switch cannot do
- Only integers and characters. You cannot switch on a float or a string.
- Only exact matches. There is no
case x > 5— that needs an if. - Each case must be a constant, not a variable.
What happens if you leave out break at the end of a case?
Create a free account to save your progress, or sign in.