Selection statements
if
if (expression)
statement
-
If expression evaluates to
non-zero (true), statement is executed.
-
If expression evaluates to 0 (false),
control passes to the statement following statement.
-
The
expression
must have scalar type.
else
if (expression1)
statement1
else if (expression2)
statement2
else
statement3
-
If expression1 is true,
statement1
is executed, and control passes to the statement following
statement3.
Otherwise,
expression2 is evaluated.
-
If expression2 is true,
statement2
is executed, and control passes to the statement following
statement3.
Otherwise,
statement3
is executed, and control passes to the statement following
statement3.
-
An else is associated with the lexically nearest
if that has no else and that is at the same block level.
switch
switch (expression)
statement
-
Control jumps to or past
statement
depending on the value of
expression.
-
expression must have integral type.
-
Any optional case is labeled by an integral
constant expression.
-
If a default case is present, it is executed if no
other case match is found.
-
If no case matches, including default,
control goes to the statement following statement.
-
If the code associated with a case is executed,
control falls through to the next case unless a
break statement is included.
-
Each case of a switch must have a unique constant
value after conversion to the type of the controlling expression.
In practice,
statement
is usually a compound statement with
multiple cases, and
possibly a default;
the description above shows the minimum usage.
In the following example, flag gets set to 1
if i is 1 or 3, and to 0 otherwise:
switch (i) {
case 1:
case 3:
flag = 1;
break;
default:
flag = 0;
}
Next topic:
Iteration statements
Previous topic:
Compound statement
© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003