Home Segments Index Top Previous Next

417: Mainline

Although there is nothing wrong with the program fragment in Segment 416, you can rewrite it, with a gain in elegance and clarity, by substituting what is called a switch statement for the if--else--if--else combination.

The purpose of a switch statement is to execute a particular sequence of statements according to the value of an expression that produces a number belonging to any of the integral types. Then, in most switch statements, integer constants and corresponding statement sequences are sandwiched between a case symbols on one end and a break statements on the other, with a colon separating the constant integer and the statement sequence:

switch (integer-producing expression) { 
  case integer constant 1: statements for integer 1 break; 
  case integer constant 2: statements for integer 2 break; 
  ... 
  default: default statements 
} 

When such a switch statement is encountered, the integer-producing expression is evaluated. The value is compared with the integer constants found following the case symbols. As soon as there is a match, evaluation of the following statements begins; evaluation continues up to the first break statement encountered.

The line beginning with the default symbol is optional. If the expression produces an integer that fails to match any of the case integer constants, the statements following the default symbol are executed.

If there is no match and no default symbol, no statements are executed.