2.3 The switch Statement
When you are testing an integer, character, or enum value and need to branch many ways on its value, a long chain of else if becomes verbose. A switch can make the structure clearer.
switch (op) {
case '+':
printf("%d\n", a + b);
break;
case '-':
printf("%d\n", a - b);
break;
default:
printf("Unsupported\n");
break;
}A switch matches the value in the parentheses against each case. Once a case matches, execution starts from there.
switch only works with integer types (int, char, enums, and so on); it cannot be used with double or strings.break and fall-through
break exits the switch. If you forget it, execution continues into the following case, a behavior called fall-through.
Sometimes you can use fall-through deliberately so several cases share the same code:
switch (grade) {
case 'A':
case 'B':
printf("Pass\n");
break;
case 'C':
printf("Just pass\n");
break;
default:
printf("Fail\n");
break;
}Here 'A' and 'B' share one output, because 'A' has no break and falls through to 'B'. Most of the time, however, a missing break is a bug, so be careful.
default
default handles every case that did not match, similar to the else in an if-else if-else. It is good practice to always include default, even if it only prints a message, so the program behaves predictably on unexpected input.