switch jumps to the case label matching an integer value. Execution falls through into the next case unless you break.
#include <stdio.h>
const char *day_type(int day) {
switch (day) {
case 0:
case 6:
return "weekend"; /* several labels share one body */
case 1: case 2: case 3: case 4: case 5:
return "weekday";
default:
return "invalid";
}
}
int main(void) {
printf("%s %s %s\n", day_type(0), day_type(3), day_type(9));
return 0;
}weekend weekday invalidFall-through
#include <stdio.h>
int main(void) {
int level = 2;
switch (level) {
case 3: printf("gold ");
/* fall through */
case 2: printf("silver ");
/* fall through */
case 1: printf("bronze ");
break;
default: printf("none");
}
printf("\n");
return 0;
}silver bronzeRules
The controlling expression must have an integer type (
int,char,enum…) — not a string ordouble.caselabels must be integer constant expressions and unique.const intvariables are not allowed in C; useenumor#define.defaultis optional and may appear anywhere; it runs when no case matches.Declaring a variable right after a
caselabel needs a block:case 1: { int t = 0; … break; }.For strings, use
if/else ifwithstrcmp.
#include <stdio.h>
enum Color { RED, GREEN, BLUE };
int main(void) {
enum Color c = GREEN;
switch (c) {
case RED: printf("stop\n"); break;
case GREEN: printf("go\n"); break;
case BLUE: printf("calm\n"); break;
}
return 0;
}goswitch vs if-else chain — which is faster?