C Language | Flow Control | switch Statement
The switch statement selects one of several code paths according to a value.
Multiple Branches
Long if else if chains are difficult to read when a program branches on many constant values. Use switch for this case.
switch (expression) {
case constant:
statements
break;
default:
default-statements
}
switch evaluates an expression and jumps to the matching case label. A case value must be a constant and cannot be duplicated. default runs when no case matches.
Without break, execution continues into the following labels. This behavior is called fall-through.
switch (0) {
case 0:
printf("case 0");
break;
case 1:
printf("case 1");
break;
default:
printf("default");
}
case and default are optional. If no label matches and there is no default, the statement does nothing.
Code 1
#include <stdio.h>
int main() {
int selected;
printf("0=first, 1=second, 2=third >");
scanf("%d", &selected);
switch(selected) {
case 0:
printf("First choice.\n");
break;
case 1:
printf("Second choice.\n");
break;
case 2:
printf("Third choice.\n");
break;
default:
printf("Enter a valid choice.\n");
}
return 0;
}
Character constants can also be used as case labels, such as case 'A':.