switch block comprises several
case labels and an optional but highly recommended
default label. Statements that follow each
case label must end with a
break statement, which is 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, omitting it produces no compiler warnings. When this behavior is unintentional, it can cause unexpected control flow.
Noncompliant Code Example
In this noncompliant code example, the case where the
11 lacks a
break statement. As a result, execution continues with the statements for
card = 12.
This compliant solution terminates each case (including the
default case) with a
Failure to include
break statements can cause unexpected control flow.
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. Nevertheless, the final case in a
switch statement should end with a
break statement in accordance with good programming style [Vermeulen 2000].
Exceptionally, when multiple cases require execution of identical code,
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:
Also, when a case ends with a
throw statement, the
break statement may be omitted.