Chapter 8 Switch Statement

When a program has to handle just two or three possible actions, an if-else if statement can be used. When there are a large number of possible actions, the switch statement is used.
switch (expression) {

case valueA: statementA1;
statementA2;
...
break;


case valueB: statementB1;
statementB2;
...
break;

default:
...
break;

}

  When a switch is compiled, the compiler creates a table of these values and associated addresses of the corresponding "cases" (code fragments). When executed, the program first evaluates expression to an integer. Then it finds it in the table and jumps to the corresponding "case." If the value is not in the table, the program jumps to "default." The break statement at the end of a case tells the program to jump out of the switch and continue with the first statement after the switch.

Switch, case, default, and break are reserved words.

  • The expression evaluated in a switch must have an integral type (integer or char).
  • All "cases" must be labeled by constants.
  • The same action may be activated by more than one constant label.
  • There may be a break in the middle of a case.
  • The default clause is optional.

    Loops and switch statments use the same break keyword. A break must always appear inside a loop or switch.