CERT-DCL41-C
In this section:
Synopsis
Do not declare variables inside a switch statement before the first case label
Enabled by default
Yes
Severity/Certainty
Medium/Low

Full description
Do not declare variables inside a switch statement before the first case label
Coding standards
- CERT DCL41-C
Do not declare variables inside a switch statement before the first case label
Code examples
The following code example fails the check and will give a warning:
#include <stdio.h>
extern void f(int i);
void func(int expr) {
switch (expr) {
int i = 4;
f(i);
case 0:
i = 17;
/* Falls through into default code */
default:
printf("%d\n", i);
}
}
The following code example passes the check and will not give a warning about this issue:
#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;
}