Explain it simply
Explain it simply
Think of switch as the button panel in a lift. Press 4 and the lift goes straight to floor 4 without asking every floor on the way. switch (day) likewise looks at day's value and jumps directly to the matching case label, or to default when nothing matches.
For a long if / else if chain that compares one variable with == against many values, such as menu options, day numbers, status codes or keyboard commands, switch is shorter and easier to read. The one habit to build is ending each case with break.
Problem → Why → Solution
The problem: one missing break ships an order
In an order system, status 1 means "paid" and status 2 means "shipped". The developer forgets the break at the end of case 1. For every freshly paid order, the program prints Payment received and then carries on to print Package shipped as well. Customers get shipping emails before anything has left the warehouse, and no test failed to warn anyone.
int status = 1; /* 1 = paid, 2 = shipped */
switch (status) {
case 1:
printf("Payment received\n");
/* break forgotten here */
case 2:
printf("Package shipped\n"); /* also runs when status is 1 */
break;
default:
printf("Unknown status\n");
}A case label is not a fenced-off block
Case labels are entry points (jump targets); they do not wall each case off into its own block. Once switch has jumped to the matching label, execution runs straight down through the following labels until it reaches a break or the switch's closing }. GCC's -Wextra can warn this statement may fall through.
Core concept: jump, run, break
switch (expression) evaluates the expression exactly once. It must have an integer type such as int, char, long or an enum; give it a double or a string and GCC refuses with error: switch quantity not an integer. Execution then jumps to the case label equal to that value. If none matches, it jumps to default, and if there is no default, nothing inside the switch runs.
Every case label must be an integer constant expression: a literal such as 4 or 'q', an enum constant, or a #define macro. A variable or a const int as a label gives error: case label does not reduce to an integer constant, and two labels with the same value give error: duplicate case value.
Since labels are only entry points, execution keeps going down until a break (which leaves the switch) or the end of the switch. This is called fall-through. Normally every case ends with break. There are two deliberate uses of fall-through: grouping, by stacking labels such as case 6: case 7: (no warning), and cumulative steps, marked with a /* fall through */ comment. GCC recognises that comment and stays quiet, and C23 adds the [[fallthrough]]; attribute for the same purpose.
default exists to catch unexpected values. It may appear anywhere, but by convention it goes last, and if it is not last it needs a break too. switch can only test equality against constants, so ranges such as score >= 80 and compound conditions stay with if...else.
| What you need | Use |
|---|---|
| Match one int, char or enum against many constants | switch |
| Ranges or conditions with && / || | if...else |
| Comparing doubles or strings | if...else |
- Evaluate the expression once
- Jump in at the matching case door
- Walk down until a break
- No match: enter at default
Cases are doors, not walls; break is the wall you have to build yourself.
General pattern
switch (integer_expression) {
case CONSTANT_A:
/* statements for A */
break;
case CONSTANT_B:
case CONSTANT_C: /* B and C share the same code */
/* statements for B or C */
break;
default:
/* anything else */
break;
}The expression must have an integer type, and each CONSTANT must be a literal, an enum constant or a macro. Stacked labels share one block of code. The break after default is optional, but it keeps you safe when someone adds a case below it later.
Example: from a day number to a day name
This program turns day = 4 into a day name. Only case 1 and case 4 are written, so every other value lands in default. After running it, try day = 1, 2 and 9, then delete the break in case 4 and watch how the output changes.
#include <stdio.h>
int main() {
int day = 4;
switch (day) {
case 1:
printf("Monday");
break;
case 4:
printf("Thursday");
break;
default:
printf("Unknown day");
}
return 0;
}Code breakdown
- Line 6
switch (day) {day is read once and its value, 4, is looked up among the labels. day is an int, which meets switch's integer-type requirement.
- Lines 7-9
case 1:day is not 1, so this label is passed over. switch does not run through the labels one by one like an if chain; it jumps straight to the matching one.
- Lines 10-12
break;Execution enters at case 4 and prints Thursday. break leaves the switch immediately, so default's Unknown day is never reached. Remove this break and the output becomes ThursdayUnknown day.
- Lines 13-14
default:Every value other than 1 and 4 arrives here. As the last label it needs no break: execution simply reaches the end of the switch.
ThursdayGrouped cases and deliberate fall-through
The first switch stacks case 6: and case 7:, so day 6 and day 7 both reach Weekend. The second switch uses a named enum type, enum Plan (BASIC = 1, so STANDARD is 2 and PREMIUM is 3). A higher plan includes everything below it, so the cases have no break and are marked /* fall through */: entering at STANDARD prints both cloud backup and email account.
#include <stdio.h>
enum Plan { BASIC = 1, STANDARD, PREMIUM };
int main(void) {
int day = 6;
switch (day) {
case 6:
case 7:
printf("Weekend\n");
break;
case 1: case 2: case 3: case 4: case 5:
printf("Weekday\n");
break;
default:
printf("Invalid day %d\n", day);
break;
}
enum Plan plan = STANDARD;
printf("Plan %d includes:\n", (int)plan);
switch (plan) {
case PREMIUM:
printf("- priority support\n");
/* fall through */
case STANDARD:
printf("- cloud backup\n");
/* fall through */
case BASIC:
printf("- email account\n");
break;
}
return 0;
}enum and switch work well together
The second switch has no default, yet it handles all three enum values. Add a new value such as ENTERPRISE to the enum without a matching case, and GCC's -Wall warns enumeration value 'ENTERPRISE' not handled in switch. A default would silence that warning, which is why enum switches often leave it out.
In real projects
Where this shows up in real projects
Command-line tools read options one character at a time and dispatch them with switch (option) { case 'v': ... case 'o': ... }; it is a shape you will see in most programs built on POSIX getopt. Embedded firmware and network protocol code write state machines as an enum switch, switch (state) { case STATE_IDLE: ... case STATE_CONNECTING: ... }, where each case decides the next state.
Emulators and interpreters dispatch each instruction with switch (opcode). When the case values are dense, a compiler can turn the switch into a jump table, so picking a case costs about the same with 3 cases or 300. Projects like these enable -Wimplicit-fallthrough (part of -Wextra) to catch forgotten breaks, and mark every intentional fall-through with a comment or an attribute.
Common mistakes
Common mistakes
1. Switching on a string or a double
If command in switch (command) is a string such as "add", GCC refuses with switch quantity not an integer and pointers are not permitted as case values. Turn the command into a single char such as 'a', or use if...else with strcmp (covered in the strings lesson).
2. Trying to write a range in a case
case score >= 80: is error: case label does not reduce to an integer constant, because the label is an expression involving a variable. GCC accepts case 80 ... 100: as an extension, but with -pedantic it says ISO C does not support range expressions in switch statements before C2Y. In portable code, write ranges with if...else.
3. Declaring a variable straight after a case label
C17 does not allow a declaration directly after a label, as in case 1: int total = 10; (C23 does). Recent GCC accepts it quietly unless you pass -pedantic, but older compilers reject it with a label can only be part of a statement and a declaration is not a statement. Wrap the case body in { }, which also limits the variable's scope to that case.
Best practices
Best practices
- Type the break first whenever you start a new case, then fill in the code above it.
- Mark every intentional fall-through with /* fall through */ and keep -Wextra on.
- Give int switches a default that reports unexpected values; enum switches may omit default to benefit from -Wswitch.
- Use enum constants rather than magic numbers as case labels.
Mini challenge
Mini challenge: days in a month
Using a month number (1-12) and a leap-year flag, work out with a switch how many days the month has. Handle an invalid month number too.
- Group the 30-day months (4, 6, 9, 11) by stacking case labels
- Write the 31-day months as one group too
- February (2) has 29 or 28 days depending on is_leap_year
- default flags an invalid month, and every case ends with break
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int month = 2;
bool is_leap_year = true;
int days;
switch (month) {
/* TODO: 30-day months, stacked labels */
/* TODO: February, using is_leap_year */
/* TODO: 31-day months, stacked labels */
/* TODO: default for invalid months (set days to 0) */
}
/* TODO: print "Invalid month: N" or "Month N has D days" */
return 0;
}Expected: With month = 2 in a leap year it prints Month 2 has 29 days. Changing month to 4, 12 and 13 gives Month 4 has 30 days, Month 12 has 31 days and Invalid month: 13.
Show hint
Labels can be stacked on one line, as in case 4: case 6: case 9: case 11:. For February, use is_leap_year ? 29 : 28.
Show solution
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int month = 2;
bool is_leap_year = true;
int days;
switch (month) {
case 4: case 6: case 9: case 11:
days = 30;
break;
case 2:
days = is_leap_year ? 29 : 28;
break;
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31;
break;
default:
days = 0;
break;
}
if (days == 0) {
printf("Invalid month: %d\n", month);
} else {
printf("Month %d has %d days\n", month, days);
}
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- switch evaluates an integer expression once, jumps to the matching case label, and goes to default when nothing matches.
- Case labels must be integer constant expressions (literals, enum constants, macros), never variables, ranges or strings.
- Without break, execution falls through into the next case, so end every case with break.
- Group cases by stacking labels, and mark intentional fall-through with /* fall through */.
GNU C compiler diagnostics — GNU Project