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.
...
In this noncompliant code example, the case where widget_type
is WE_W
lacks a break
statement. Consequently, statements that should only be executed only 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 */ /* handleHandle error condition */ } |
Compliant Solution
...
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 */ /* handleHandle error condition */ } |
A break
statement is not required following the case where widget_type
is WE_Y
because there are no statements before the next case label, indicating that both WE_Y
and WE_Z
should be handled in the same fashion.
...
Code Block | ||||
---|---|---|---|---|
| ||||
enum WidgetEnum { WE_W, WE_X, WE_Y, WE_Z } widget_type; widget_type = WE_X; switch (widget_type) { case WE_W: /* ... */ /* noNo break, process case for WE_X as well */ case WE_X: /* ... */ break; case WE_Y: case WE_Z: /* ... */ break; default: /* can't happen */ /* handleHandle error condition */ } |
Risk Assessment
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
|
| ||||||
| MISSING_BREAK | Can find instances of missing break statement between cases in switch statement. | |||||||
| swchsynt | Fully implemented. |
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
...
...
...
...
...