Versions Compared

Key

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

A switch statement consists of several case labellabels, 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 end ends with a break; statement; if omitted, control flow falls through to the next case in the switch statement block. Since Because the break statement is not required, omitting the break statement it does not produce compiler warnings, and thus can produce diagnostics. If the omission was unintentional, this can result in an unexpected control flow.

Noncompliant Code Example

In this noncompliant code example, the case for when where widget_type is WE_W lacks a break statement. Consequently, the statementsfor statements that should only be executed when widget_type is WE_X get are executed even when widget_type is WE_W.

Code Block
bgColor#FFCCCC
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: /* can't happen */
	 /* handle error condition */
}

...

Code Block
bgColor#CCCCFF
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: /* can't happen */
	 /* handle error condition */
}

...