Do not include any executable statements inside a switch statement before the first case label. Such statements are never executed because the compiler ignores themAccording to the C Standard, subclause 6.8.4.2 paragraph 4,
A switch statement causes control to jump to, into, or past the statement that is the switch body, depending on the value of a controlling expression, and on the presence of a default label and the values of any case labels on or in the switch body.
If a programmer declares variables, initializes them before the first case statement, and then tries to use them inside any of the case statements, those variables will have scope inside the switch block but will not be initialized and will consequently contain garbage values.
...
When the preceding example is executed on GCC version 4.8.1.2, the variable i is instantiated with automatic storage duration within the block, but it is not initialized. Consequently, if the controlling expression has a nonzero value, the call to printf() will access an indeterminate value of i. Similarly, the call to f() is not executed.
...
In this compliant solution, the statements before the first case label occur before the switch statement, improving the predictability and readability of the code:
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdio.h>
extern void f(int i);
int func(int expr) {
/* Move the code outside the switch block, now the statements
will get executed. */
int i = 4;
f(i);
switch(expr) {
case 0:
i = 17;
/* Falls through into default code */
default:
printf("€œ%d\n"€, i);
}
return 0;
}
|
...
Using test conditions or initializing variables before the first case statement in a switch block can result in unexpected behavior because that code will not be executed.
RecommendationRule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
MSC35-C | mediumMedium | unlikelyUnlikely | mediumMedium | P4 | L3 |
Related Vulnerabilities
...
| MISRA C:2012 | Rule 16.1 (required) |
Bibliography
| [ISO/IEC 9899:2011] | Subclause 6.8.4.2, "The switch Statement" |