C Switch
When one value is compared with a list of fixed numbers or characters, switch is often clearer than a long chain of else if.
How switch works
switch looks at one value and jumps to the case with the same value. break ends the switch. default runs when no case matches.
#include <stdio.h>
int main(void) {
int day;
printf("Day number (1-7): ");
scanf("%d", &day);
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:
case 7: printf("Weekend!\n"); break;
default: printf("There is no day %d\n", day);
}
return 0;
}3
Day number (1-7): Wednesday
Cases 6 and 7 share the same code: when there is no break after case 6:, the program falls through into case 7:. That is useful here, but a forgotten break is a common bug: the program then also runs the next case.
Characters in a switch
switch works with any whole number value, including characters:
#include <stdio.h>
int main(void) {
char op = '*';
int a = 6, b = 3;
switch (op) {
case '+': printf("%d\n", a + b); break;
case '-': printf("%d\n", a - b); break;
case '*': printf("%d\n", a * b); break;
case '/': printf("%d\n", a / b); break;
default: printf("Unknown operator %c\n", op);
}
return 0;
}18
When not to use switch
The cases must be constant values: case 1: or case 'a':, not case marks >= 90:. For ranges, strings or combined conditions, use if and else if instead. A switch cannot compare strings; use strcmp from the String Functions topic.
Variables inside a case
If a case needs its own variable, put the case's code in curly braces: case 1: { int x = 5; ... break; }. Without the braces the compiler complains that a jump goes past the variable's declaration.
Practice exercises
- Write a menu: 1 adds two numbers, 2 subtracts, 3 multiplies, anything else prints an error.
- Read a letter and print whether it is a vowel, using cases that fall through for
a,e,i,oandu. - Remove one
breakfrom the day example, run it, and explain the output.