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 next statement statements in the subsequent case
label gets get executed. Because the break
statement is optional, its omission produces no compiler warnings. If this behavior is unintentional, it can lead to undesirable control flowscause unexpected control flow.
Noncompliant Code Example
In this noncompliant code example, the case wherein the card
is 11 does not have a break
statement. As a result, the statements for card = 12
are also executed when card = 11
.
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; } |
...
Exceptions
EX1: The last label in a switch
statement requires no break
. The break
statement serves to skip to the end of the switch
block, so control flow will continue transfers to statements following the switch
block with or without itirrespective of its presence. Conventionally, the last label is the default
label.
EX2: In some cases, where control flow is intended When it is required to execute the same code for multiple cases, it is permissible to omit the break
statement. However, these instances must be explicitly documented.
...
Risk Assessment
Failure to include break
statements leads to may cause unexpected control flow.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC08- J | medium | unlikely | low | P6 | L2 |
...