Tuesday, January 3, 2012

What does the switch statement do?

What does the switch statement do?

A switch statement or switch control structure is constructed similarly to the if-else-if control structure. It also is used to transfer control. Its syntax is:

switch(expression)
{
case constant1:
statement1a
statement1b
...
case constant2:
statement2a
statement2b
...
...
default:
statements
}

where the expression must be enclosed in a pair of parenthesis and must result in an integer type value when the program flow enters the switch block. A switch block must be bounded by a pair of braces. The terms constant1, constant2, and so on are integer type constant expressions. Note that all constant expressions are followed by colons. All the constant expressions must be unique, meaning that none can have the same value as another constant expression. Although not required, it is common that the last case type line is the keyword default. If no constant matches the value of the expression, the statements in the default case are executed. The default case is optional. If no default case is given and no constant matches the number, the entire switch block is ignored.

No comments:

Post a Comment