Name
switch
Synopsis
In a switch
statement, the value of the
switch
expression is compared to the constants
associated with case
labels. If the expression
evaluates to the constant associated with a case label, program
execution continues at the matching label. If no matching label is
present, program execution branches to the default label if present;
otherwise execution continues with the statement following the switch
statement.
Syntax:
switch (
expression
)
statement
The expression
is an integer expression
and statement
is a block statement with
case
labels and at most one
default
label. Every case
label
has the form case
const
:
, where
const
is a constant integer expression.
All case
constants must be different from one
another.
Example:
switch( command ) // Query a command obtained { // by user input in a menu, // for example. case 'a': case 'A': action1(); // Carry out action 1, break; // then quit the switch. case 'b': case 'B': action2(); // Carry out action 2, break; // then quit the switch. default: putchar('\a'); // On any other "command": // alert. }
After the jump from the switch
to a label, program
execution continues sequentially, regardless of other labels. The
break
statement can be used to exit the
switch
block at any time. A
break
is thus necessary if the statements
following other case
labels are not to be
executed.
Integer promotion is applied to the switch
expression. The case
constants are then converted
to the resulting type of the switch
expression.
Get C Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.