BLOCKS AND STATEMENTS
The
switch
Statement
14.9
Every
case
constant expression associated with a
switch
statement must be
assignable ( 5.2) to the type of the
switch
Expression
.
No two of the
case
constant expressions associated with a
switch
statement
may have the same value.
At most one
default
label may be associated with the same
switch
state
ment.
In C and C++ the body of a
switch
statement can be a statement and state
ments with
case
labels do not have to be immediately contained by that state
ment. Consider the simple loop:
for (i = 0; i < n; ++i) foo();
where
n
is known to be positive. A trick known as
Duff's device
can be used in C
or C++ to unroll the loop, but this is not valid Java code:
int q = (n+7)/8;
switch (n%8) {
case 0:
do {
foo();
//
Great C hack, Tom,
case 7:
foo();
//
but it's not valid in Java.
case 6:
foo();
case 5:
foo();
case 4:
foo();
case 3:
foo();
case 2:
foo();
case 1:
foo();
} while ( q >= 0);
}
Fortunately, this trick does not seem to be widely known or used. Moreover, it is
less needed nowadays; this sort of code transformation is properly in the province
of state of the art optimizing compilers.
When the
switch
statement is executed, first the
Expression
is evaluated. If
evaluation of the
Expression
completes abruptly for some reason, the
switch
statement completes abruptly for the same reason. Otherwise, execution continues
by comparing the value of the
Expression
with each
case
constant. Then there is a
choice:
If one of the
case
constants is equal to the value of the expression, then we
say that the
case
matches, and all statements after the matching
case
label in
the switch block, if any, are executed in sequence. If all these statements com
plete normally, or if there are no statements after the matching
case
label,
then the entire
switch
statement completes normally.
275
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved