switch (expression)
{
case value1:
statements
case value2:
statements
...
default: statements
}
If the expression evaluates to value1
, execution inside the braces starts after the label value1:
. Similarly for any other values that are given as case
s. If none of the case values matches, the default
section is executed.
The default
section is optional. If it is not there, execution just continues after the ending brace of the switch
.
switch (keyCode)
{
case insKey: insert ();
break;
case backKey:
case delKey: delete ();
break;
default: append (keyCode);
}
It is usual to put break;
at the end of each section to make execution jump out there and continue after the ending brace of the switch
. If the break;
is not there, execution continues into the next case section; sometimes that is desired, as in the backKey
case in the example above.
switch (expression)
must evaluate to byte, short, int or char. Not boolean, float, double or long.case value:
. No run-time expressions.