Switch statements
When the same (integer) expression is compared against a number of distinct
values,
it's preferred to evaluate the expression once,
and compare it with possible values:
Cascading if..else..if.. statements:
|
The equivalent switch statement:
|
Less-common features of the switch statement:
|
if(expression == value1) {
// more statements;
.....
}
else if(expression == value2) {
// more statements;
.....
}
else {
// more statements;
.....
}
|
|
switch (expression) {
case value1 :
// more statements;
.....
break;
case value2 :
// more statements;
.....
break;
default :
// more statements;
.....
break;
}
|
|
switch (expression) {
case value1 :
case value2 :
// handle either value1 or value2
.....
break;
case value3 :
// more statements;
.....
// no 'break' statement, drop through
default :
// more statements;
.....
break;
}
|
|
- Typically the 'expression' is simply an identifier,
but it may be arbitrarily complex - such as an arithmetic expression,
or a function call.
- The datatype of the 'expression' must be an integer
(which includes characters, Booleans, and enumerated types),
but it cannot be a real or floating-point datatype.
- The break statement at the end of each case
indicates that we have finished with the 'current' value,
and control-flow leaves the switch statement.
Without a break statement,
control-flow continues "downwards",
flowing into the next case branch
(even though the expression does not have that case's value!).
- switch statements with 'dense' values
(none, or few integer missing)
provide good opportunities for optimised code.
- There is no need to introduce a new block,
with curly-brackets,
unless you need to define new local variables for specific
case branches.
CITS2002 Systems Programming, Lecture 2, p11, 24th July 2024.
|