10.12.2012 Views

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

The Java Language Specification, Third Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

14.11 <strong>The</strong> switch Statement BLOCKS AND STATEMENTS<br />

378<br />

• No two of the case constant expressions associated with a switch statement<br />

may have the same value.<br />

• At most one default label may be associated with the same switch statement.<br />

DISCUSSION<br />

<strong>The</strong> prohibition against using null as a switch label prevents one from writing code that can<br />

never be executed. If the switch expression is of a reference type, such as a boxed primitive<br />

type or an enum, a run-time error will occur if the expression evaluates to null at run-time.<br />

It follows that if the switch expression is of an enum type, the possible values of the<br />

switch labels must all be enum constants of that type.<br />

Compilers are encouraged (but not required) to provide a warning if a switch on an<br />

enum-valued expression lacks a default case and lacks cases for one or more of the enum<br />

type’s constants. (Such a statement will silently do nothing if the expression evaluates to<br />

one of the missing constants.)<br />

In C and C++ the body of a switch statement can be a statement and statements<br />

with case labels do not have to be immediately contained by that statement.<br />

Consider the simple loop:<br />

for (i = 0; i < n; ++i) foo();<br />

where n is known to be positive. A trick known as Duff’s device can be used in C<br />

or C++ to unroll the loop, but this is not valid code in the <strong>Java</strong> programming language:<br />

int q = (n+7)/8;<br />

switch (n%8) {<br />

case 0: do {foo(); // Great C hack, Tom,<br />

case 7: foo(); // but it’s not valid here.<br />

case 6: foo();<br />

case 5: foo();<br />

case 4: foo();<br />

case 3: foo();<br />

case 2: foo();<br />

case 1: foo();<br />

} while (--q > 0);<br />

}<br />

Fortunately, this trick does not seem to be widely known or used. Moreover, it is<br />

less needed nowadays; this sort of code transformation is properly in the province<br />

of state-of-the-art optimizing compilers.<br />

DRAFT

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!