Versions Compared

Key

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

A switch statement consists of several case labels, plus a default label. The default label is optional but recommended. (See MSC01-C. Strive for logical completeness.) A series of statements following a case label conventionally ends with a break statement; if omitted, control flow falls through to the next case in the switch statement block. Because the break statement is not required, omitting it does not produce compiler diagnostics. If the omission was unintentional, it can result in an unexpected control flow.

...

Code Block
bgColor#FFCCCC
langc
enum WidgetEnum { WE_W, WE_X, WE_Y, WE_Z } widget_type;
widget_type = WE_X;

switch (widget_type) {
  case WE_W:
    /* ... */
  case WE_X:
    /* ... */
    break;
  case WE_Y: 
  case WE_Z:
    /* ... */
    break;
  default: /* canCan't happen */
	 /* Handle error condition */
}

...

Code Block
bgColor#CCCCFF
langc
enum WidgetEnum { WE_W, WE_X, WE_Y, WE_Z } widget_type;
widget_type = WE_X;

switch (widget_type) {
  case WE_W:
    /* ... */
    break;
  case WE_X:
    /* ... */
    break;
  case WE_Y: 
  case WE_Z:
    /* ... */
    break;
  default: /* canCan't happen */
	 /* Handle error condition */
}

...

A break statement is not required following the default case because it would not affect the control flow.

Exceptions

MSC17-EX1: The last label in a switch statement requires no final break. It will conventionally be the default label.

MSC17-EX2: When control flow is intended to cross statement labels, it is permissible to omit the break statement. In these instances, the unusual control flow must be explicitly documented.

Code Block
bgColor#CCCCFF
langc
enum WidgetEnum { WE_W, WE_X, WE_Y, WE_Z } widget_type;
widget_type = WE_X;

switch (widget_type) {
  case WE_W:
    /* ... */
    /* No break,; process case for WE_X as well */
  case WE_X:
    /* ... */
    break;
  case WE_Y: case WE_Z:
    /* ... */
    break;
  default: /* canCan't happen */
	 /* Handle error condition */
}

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC17-C

mediumMedium

likelyLikely

lowLow

P18

L1

Automated Detection

Tool

Version

Checker

Description

Compass/ROSE

 

 

 

Coverity

Include Page
Coverity_V
Coverity_V

MISSING_BREAK

Can find instances of missing break statement between cases in switch statement

ECLAIR

Include Page
ECLAIR_V
ECLAIR_V

CC2.MSC17

Fully implemented

...

 

...

Image Modified