A switch
block comprises several case
labels and an optional but highly recommended default
label. By convention, statements that follow each case label end with a break
statement, responsible for transferring the control to the end of the switch
block. When omitted, the statements in the subsequent case
label are executed. Because the break
statement is optional, its omission omitting it produces no compiler warnings. If When this behavior is unintentional, it can cause unexpected control flow.
...
In this noncompliant code example, the case wherein the card
is 11, does not have lacks a break
statement. As a result, execution continues with the statements for card = 12
are also executed.
Code Block | ||
---|---|---|
| ||
int card = 11; switch (card) { /* ... */ case 11: System.out.println("Jack"); case 12: System.out.println("Queen"); break; case 13: System.out.println("King"); break; default: System.out.println("Invalid Card"); break; } |
...
Wiki Markup |
---|
*MSC14-EX1*: The {{break}} statement at the end of the final case in a {{switch}} statement may be omitted; by convention, this is the {{default}} label. The {{break}} statement serves to transfer control to the end of the {{switch}} block; fall-through behavior also causes control to arrive at the end of the {{switch}} block. Consequently, control transfers to the statements following the {{switch}} block without regard to the presence or absence of the {{break}} statement. Conventionally, the last label is the {{default}} label. Nevertheless, the final case in a {{switch}} statement should end with a {{break}} statement, in accordance with good programming style (see \[[Rogue 2000|AA. Bibliography#Rogue 00]\]). |
...
Failure to include break
statements may can cause unexpected control flow.
...