HP C/iX Reference Manual (31506-90011)

Chapter 6 87
Statements
The switch Statement
The switch Statement
The switch statement executes one or more of a series of cases based on the value of an
expression. It offers multiway branching.
Syntax
switch (
expression
)
statement
Description
The
expression
after the word switch is the controlling expression. The controlling
expression must have integral type. The statement following the controlling expression is
typically a compound statement. The compound statement is called the switch body.
The statements in the switch body may be labeled with case labels. The case label is
followed by an integral constant expression and a colon. No two case constant expressions
in the same switch statment may have the same value.
When the switch statement executes, integral promotions are performed on the
controlling expression; the result is compared with the constant expressions after the case
labels in the switch body. If one of the constant expressions matches the value of the
controlling expression, control passes to the statement following that case expression.
If no expression matches the value of the control expression and a statement in the switch
body is labeled with the default label, control passes to that statement. Only one
statement of the switch body may be labeled the default. By convention, the default
label is included last after the case labels, although this is not required by the C
programming language.
If there is no default, control passes to the statement immediately following the switch
body and the switch effectively becomes a no-operation statement.
The switch statement operates like a multiway else-if chain except the values in the
case statements must be constant expressions, and, most importantly, once a statement is
selected from within the switch body, control is passed from statement to statement as in
a normal C program. Control may "fall" through to following case statements. Using a
break statement is the most common way to leave a switch body. If a break statement is
encountered, control passes to the statement immediately following the switch body.
Example
The following example shows a switch statement that includes several case labels. The
program selects the case whose constant matches getchar.
switch (getchar())
{
case 'r':
case 'R':
moveright ( );