...
In this noncompliant code example, the case where widget_type
is WE_W
lacks a break statement. Consequently, statements that should only be executed when widget_type
is WE_X
are executed even when widget_type
is WE_W
.
Code Block | ||||
---|---|---|---|---|
| ||||
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 */ } |
...
In this compliant solution, each sequence of statements following a case label ends with a break
statement.
Code Block | ||||
---|---|---|---|---|
| ||||
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 */ } |
...
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 | ||||
---|---|---|---|---|
| ||||
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: /* can't happen */ /* handle error condition */ } |
...