...
Section 6.8.4.2, paragraph 2, of the C Standard [ISO/IEC 9899:2011] says,
If a switch statement has an associated case or default label within the scope of an identifier with a variably modified type, the entire switch statement shall be within the scope of that identifier.154)
Footnote 154 says:
That is, the declaration either precedes the switch statement, or it follows the last case or default label associated with the switch that is in the block containing the declaration.
...
Code Block | ||||
---|---|---|---|---|
| ||||
int f(int i) { int j=0; switch (i) { case 1: for(j=0;j<10;j++) { // noNo break, process case 2 as well case 2: // switch jumps inside the for block j++; // noNo break, process case 3 as well case 3: j++; } break; default: // defaultDefault action break; } return j; } |
...
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 Other values | 0 |
Compliant Code Example
...
Code Block | ||||
---|---|---|---|---|
| ||||
int f(int i) { int j=0; switch (i) { case 1: // noNo break, process case 2 as well case 2: j++; // noNo break, process case 3 as well case 3: j++; break; default: // defaultDefault action return j; } for(j++;j<10;j++) { j+=2; } return j; } |
...
Code Block |
---|
size_t count; /* mustMust be nonzero */ char *to; /* outputOutput destination */ char *from; /* Points to count bytes to copy */ do { *to = *from++; /* Note that the "to" pointer is NOT incremented */ } while (--count > 0); |
...
The code is widely considered to be legal C and C++ and is 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.
Compliant Code Example (Duff's Device)
This is an alternate alternative implementation of Duff's device, which separates the switch
statement and loop.
...
CERT C++ Secure Coding Standard | MSC20-CPP. Do not use a switch statement to transfer control into a complex block |
ISO/IEC TR 24731-1:2007 | |
MISRA-C | Rule 15.1 |
Bibliography
[ISO/IEC 9899:2011] | Section 6.8.6.1, "The goto statement Statement" |
[ISO/IEC TR 24731-1:2007] |
|
Tom Duff on Duff's Device |