...
If a programmer declares variables and initializes them before the first case statement and try 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.
Non Compliant Code:
In the The example code mentioned below , the variable i is instantiated with automatic storage duration within the block, but is not initialized. Consequently, if the controlling expression has a non-zero value, the call to ((printf()}} will access an indeterminate value of i. Similarly, the call to function will also never get executed.declares variables and write executable code before the first case statement in the switch loop.
| Code Block | ||
|---|---|---|
| ||
int func(int expr) {
switch(expr){
int i = 4;
f(i);
case 0:
i = 17;
/*falls through into default code */
default:
printf(“%d\nâ€, i);
}
return 0;
}
|
Implementation Details
In the above example, the variable i is instantiated with automatic storage duration within the block, but is not initialized. Consequently, if the controlling expression has a non-zero value, the call to ((printf()}} will access an indeterminate value of i. Similarly, the call to function will also never get executed.
| |
|---|---|
0 | 17 |
nonzero | indeterminate |
Compliant Solution
In this compliant solution, the statements before the first case statement are moved outside the switch block, improving the predictability and readability of the code.
...
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
| Medium | unlikely | medium | P2 | L3 |
References
MISRA 04 chapter 6.14