...
The examples here fall under the exception MSC17-C-EX2 in MSC17-C. Finish every set of statements associated with a case label with a break statement.
...
When i = 1
, the entire for
loop is executed. When i = 2
, two increments to j
are made before the loop starts. When i = 3
, one increment to j
is made before the loop starts. The default case is no loop. Consequently, the function has the following behavior:
|
|
---|---|
1 | 12 |
2 | 12 |
3 | 11 |
Other values | 0 |
Compliant Solution
The compliant solution separates the switch
and for
blocks:
...
Code Block | ||||
---|---|---|---|---|
| ||||
int n = (count + 7) / 8; switch (count % 8) { case 0: *to = *from++; /* Fall through */ case 7: *to = *from++; /* Fall through */ case 6: *to = *from++; /* Fall through */ case 5: *to = *from++; /* Fall through */ case 4: *to = *from++; /* Fall through */ case 3: *to = *from++; /* Fall through */ case 2: *to = *from++; /* Fall through */ case 1: *to = *from++; /* Fall through */ } while (--n > 0) { *to = *from++; *to = *from++; *to = *from++; *to = *from++; *to = *from++; *to = *from++; *to = *from++; *to = *from++; } |
Risk Assessment
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
MSC20-C | Medium | Probable | Medium | P8 | L2 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Astrée |
| switch-label | Fully checked | ||||||
CodeSonar |
| LANG.STRUCT.SW.MPC | Misplaced case | ||||||
| CC2.MSC20 | Fully implemented | |||||||
Helix QAC |
| C2019 | |||||||
LDRA tool suite |
| 245 S | Fully implemented |
PC-lint Plus |
| 646, 9055 | Fully supported | ||||||
Polyspace Bug Finder |
| CERT C: Rec. MSC20-C | Checks for situations where switch label is not at the outermost level of switch statement body (rec. fully covered) | ||||||
RuleChecker |
| switch-label | Fully checked | ||||||
SonarQube C/C++ Plugin |
| S1036 |
Related Guidelines
SEI CERT C++ Coding Standard | VOID MSC20-CPP. Do not use a switch statement to transfer control into a complex block |
ISO/IEC TR 24731-1:2007 |
MISRA C:2012 |
Rule 16.2 (required) |
Bibliography
[ISO/IEC 9899:2011] | Subclause 6.8.6.1, "The goto Statement" |
[Duff 1988] | Tom Duff on Duff's Device |
...
...