Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 get executed. Because the break statement is optional, its omission produces no compiler warnings. If this behavior is unintentional, it can cause 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.

Code Block
bgColor#FFCCCC
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;
}

Compliant Solution

This compliant solution terminates each case (including the default case) by a break statement.

Code Block
bgColor#CCCCFF
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;
}

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 transfers to statements following the switch block irrespective of its presence. Conventionally, the last label is the default label.

...

EX3: A case needs no break statement if its last statement is a return or throw.

Risk Assessment

Failure to include break statements may cause unexpected control flow.

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC06- J

medium

unlikely

low

P6

L2

Other Languages

This rule appears in the C Secure Coding Standard as MSC17-C. Finish every set of statements associated with a case label with a break statement.

This rule appears in the C++ Secure Coding Standard as MSC18-CPP. Finish every set of statements associated with a case label with a break statement.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] [Section 14.11 The switch Statement|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.11]

...