if( <expression> == <constant1> ) <do_something>
else if( <expression> == <constant2> ) <do_something_else>
else if( <expression> == <constant3> ) <do_yet_another_thing>
...
else <do_the_last_resort>
The above code sequence can be written as:
switch(<expression>)
{ case <constant1>: <do_something>
break;
case <constant2>: <do_something_else>
break;
case <constant3>: <do_yet_another_thing>
break;
...
default : <do_the_last_resort>
}
When the break statement occurring in the compound statement in a switch (or while) is executed, it causes the compound statement to terminate immediately.
For example, if the <expression > evaluated to a value that matched <constant2 > the switch would begin with <do_something_else >, and then execute the break, ending the switch statement.
If on the other hand, we left the breaks out:
switch(<expression>)
{ case <constant1>: <do_something>
case <constant2>: <do_something_else>
case <constant3>: <do_yet_another_thing>
...
default : <do_the_last_resort>
}
switch(<expression>)
{ case <constant1>:
case <constant2>:
...
case <constantn>: <do_something>
break;
default : <do_the_last_resort>
}
The switch statement takes the form:
switch( <expression> ) <statement>
where:
switch is a keyword.followed by a paranthesized expression which evaluates to an integer value.and the statement.
where the <statement> is almost always a compound statement with case labels inside. We saw compound statements in while loops.
A case label takes the form:
case <constant>:
or
default:
where <constant> MUST be an integer valued, compile time constant.
These are NOT executable statements; the case label is simply a "marker" on some statement in the code. Within a switch, all case labels must be unique.
Evaluate the expression and find the case label which matches the integer value. If none match, then the default label is used. Begin executing the compound statement at the matching label. Execution will continue in the compound statment until its end, or until a break statement is executed.