...
C99, Section 6.8.6.1 "The goto statement", says:
A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier.
...
The examples here fall under the exception MSC17:-EX2 in MSC17-C. Finish every set of statements associated with a case label with a break statement.
...
This example shows the use of the switch statment statement to jump into a for loop.
| Code Block | ||
|---|---|---|
| ||
int f(int i) {
int j=0;
switch (i) {
case 1:
for(j=0;j<10;j++) {
// no break, process case 2 as well
case 2: // switch jumps inside the for block
j++;
// no break, process case 3 as well
case 3:
j++;
}
break;
default:
// default action
break;
}
return j;
}
|
...
In this code, the first iteration of the loop is subject to the switch statement, so it performs count % 8 assignments. Each subsequent iteration of the loop performs 8 assignments. (being Being outside the loop, the switch statement is ignored.) . Consequently, this code performs count assignments, but only n comparisons, so it is usually faster.
The code is widely considered to be legal C and C++ and supported by all compliant compilers. When describing Duff's Device, the creator noted:
Many people ... have said that the worst feature of C is that switches don't break automatically before each case label. This code forms some sort of argument in that debate, but I'm not sure whether it's for or against.
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
MSC20-C | medium | probable | medium | P8 | L2 |
Other Languages
Related Guidelines
This rule appears in the C++ Secure Coding Standard as : MSC20-CPP. Do not use a switch statement to transfer control into a complex block.
Bibliography
| Wiki Markup |
|---|
\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 6.8.6.1 "The goto statement" [MISRA 042004|AA. Bibliography#ISO/MISRA 04] Rule 15.1 [Tom Duff on Duff's Device|http://www.lysator.liu.se/c/duffs-device.html] |
...