...
This compliant solution terminates each case (including the default
case) with a break
statement.:
Code Block | ||
---|---|---|
| ||
int card = 11; switch (card) { /* ... */ case 11: System.out.println("Jack"); break; case 12: System.out.println("Queen"); break; case 13: System.out.println("King"); break; default: System.out.println("Invalid Card"); break; } |
...
Exceptionally, when multiple cases require execution of identical code, then break
statements may be omitted from all cases except the last one. Similarly, when processing for one case is a proper prefix of processing for one or more other cases, the break
statement may be omitted from the prefix case. This should be clearly indicated with a comment. For example:
Code Block | ||
---|---|---|
| ||
int card = 11; int value; // Cases 11,12,13 fall through to the same case switch (card) { // processingProcessing for this case requires a prefix // of the actions for the following three case 10: do_something(card); // intentionalIntentional fall-through // theseThese three cases are treated identically case 11: // breakBreak not required case 12: // breakBreak not required case 13: value = 10; break; // breakBreak required default: // Handle Errorerror Conditioncondition } |
Also, when a case ends with a return
or throw
statement, the break
statement may be omitted.
Related Guidelines
"CLL Switch Statements and Static Analysis "[CLL] | |
CWE-484, " Omitted Break Statement in Switch"break statement in switch | |
[Rogue 2000] | Rule 78, The Elements of Java Style, Rule 78. |
Bibliography
...