RED-local-hides-local
In this section:
Synopsis
The definition of a local variable hides a previous local definition.
Enabled by default
No
Severity/Certainty
Medium/Medium

Full description
A local variable is declared with the same name as another local variable, hiding the outer value from this scope, from this point onwards. This might be intentional, but it is better to use a different name for the second variable, so that a reference to the outer variable does not accidentally change or return the inner value.
Coding standards
- CERT DCL01-C
Do not reuse variable names in subscopes
- CERT DCL01-CPP
Do not reuse variable names in subscopes
Code examples
The following code example fails the check and will give a warning:
int foo(int x ) {
for (int y= 0; y < 10 ; y++){
for (int y = 0; y < 100; y ++){
return x+y;
}
}
return x;
}
int foo2(int x) {
int y = 10;
for (int y= 0; y < 10 ; y++)
x++;
return x;
}
int foo3(int x) {
int y = 10;
{
int y = 100;
return x + y;
}
}
The following code example passes the check and will not give a warning about this issue:
int foo(int x){
for (int y=0; y < 10; y++)
x++;
for (int y=0; y < 10; y++)
x++;
return x;
}