switch / case / break / default
Branches execution based on the value of an integer or character. When switching between multiple values, switch / case is cleaner to write than a chain of if / else if statements.
Syntax
switch (expression) {
case value1:
process1;
break;
case value2:
process2;
break;
case value3:
case value4:
process3; // Runs for both value3 and value4 (fall-through).
break;
default:
default process;
break;
}
Keywords
| Keyword | Description |
|---|---|
| switch | Evaluates an expression and jumps to the matching case. The expression must be an integer type (such as int, char, or enum). Floating-point numbers and strings are not supported. |
| case | Specifies a constant value to compare against. The statements to execute follow a colon. The value must be a constant (a literal or constant expression). |
| break | Exits the switch block. If omitted, execution continues into the next case (fall-through). |
| default | Executed when no case matches. It is optional, but recommended as a safeguard against unexpected values. |
Sample Code
#include <stdio.h>
int main(void) {
// Branch on an integer value.
int day = 3;
switch (day) {
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break; // Prints "Wednesday".
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 value.\n"); break;
}
// Also works with char.
char grade = 'B';
switch (grade) {
case 'A': printf("Excellent.\n"); break;
case 'B': printf("Good.\n"); break; // Prints "Good."
case 'C': printf("Pass.\n"); break;
default: printf("Fail.\n"); break;
}
// Use fall-through to handle multiple values together.
int month = 4;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
printf("31 days.\n"); break;
case 4:
case 6:
case 9:
case 11:
printf("30 days.\n"); break; // Prints "30 days."
case 2:
printf("28 or 29 days.\n"); break;
default:
printf("Invalid month.\n"); break;
}
return 0;
}
Notes
switch is often implemented internally using a jump table, which makes it more efficient than if / else if when there are many branches. If you forget to write break, execution will unintentionally continue into the next case (fall-through). Always write break unless the fall-through is intentional.
The switch expression only accepts integer types (int, char, enum, etc.). Strings and floating-point numbers are not supported — use if / else for those cases.
When grouping related values, combining switch with enum improves code readability.
If you find any errors or copyright issues, please contact us.