2.3 switch

A switch statement is a multiway switch. The general form looks like this:

'switch' '('<int-expr>')'
'{'
  {'case' <const-expr>':' <stmt>*}*
  ['default:'
    <stmt>*]
'}'

In this notation, {...} encloses a sequence (note the lack of quotes around the braces). This construct is useful, because we can then use {...}* (note the asterisk) to indicate the sequence in braces can repeat any number of times (including zero).

<int-expr> is an expression that evaluates to an integer value. This is used to control which case statement gets control. <const-expr> is an expression that evalutes to a constant. This means that it cannot rely on anything that may change during run-time.

The optional default case gets control when no case statement executes.

Note that in a switch statement, at the end of a case, execution falls through to the next case or default block. This is why most case blocks end with a break statement.



Copyright © 2006-09-25 by Tak Auyeung