
Do not include any executable statements inside a switch statement before the first case label. Such statements are never executed because the compiler ignores them.
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.
Noncompliant Code Example
This noncompliant code example declares variables and contains executable statements before the first case label within the switch statement.
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
When the above example is executed on GCC Version 4.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 non-zero value, the call to printf()
will access an indeterminate value of i
. Similarly, the call to f()
is not executed.
|
|
---|---|
0 |
17 |
non-zero |
indeterminate |
Compliant Solution
In this compliant solution, the statements before the first case label occur before the switch statement, improving the predictability and readability of the code.
int func(int expr) { int i = 4; /* Move the code outside the switch block */ f(i); /* Now the statements will get executed */ switch(expr) { case 0: i = 17; /*falls through into default code */ default: printf(â%d\nâ, i); } return 0; }
Risk Assessment
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.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
MSC35-C |
medium |
unlikely |
medium |
P4 |
L3 |
Related Guidelines
MISRA Chapter 6.14