Switch Statement in C
On this page (11sections)
About this page
This is a tutorial in C Controls — switch, case, break, and fall-through behaviour. For runnable examples, see Switch Case Example Program and Weekdays Switch Program.
Introduction
The switch statement selects one of many code branches based on the value of an integer expression. It is cleaner than a long if-else-if chain when comparing one variable against many constant values.
Syntax
switch (expression) {
case constant1:
/* statements */
break;
case constant2:
/* statements */
break;
default:
/* optional — runs if no case matches */
break;
}
Example — Weekday Name
#include <stdio.h>
int main(void) {
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
case 6: printf("Saturday\n"); break;
case 7: printf("Sunday\n"); break;
default: printf("Invalid day\n");
}
return 0;
}
Sample Output
Wednesday
The break Statement
break exits the switch immediately. Without it, execution falls through to the next case:
switch (ch) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
printf("Vowel\n");
break;
default:
printf("Consonant or other\n");
}
Fall-through is intentional here — multiple cases share one block.
switch vs if-else-if
| Use switch when | Use if-else when |
|---|---|
| Testing one variable against constants | Comparing ranges (score >= 80) |
| Many discrete values (menu options, days) | Complex boolean conditions |
| Integer or char type | Any expression |
Best Practices
- Always include
breakunless fall-through is intentional (add a comment). - Include a
defaultcase to handle unexpected values. - Keep case bodies short — call a function for complex logic.
- Group related cases without break between them.
Common Mistakes
- Missing
breakcausing unintended fall-through. - Using non-constant expressions in
caselabels. - Testing floating-point values with switch (not allowed in C).
Related Programs
See Switch Case Example Program and Weekdays Switch Program.
Frequently Asked Questions
What types can switch test in C?
switch works with integer types: int, char, short, long, and enum. It cannot test float, double, or strings directly.
Why is break required in switch?
Without break, execution falls through to the next case. break exits the switch after a matching case runs.