Why is this an issue?
Overriding or shadowing a variable declared in an outer scope can strongly impact the readability, and therefore the maintainability, of a piece of
code. Further, it could lead maintainers to introduce bugs because they think they’re using one variable but are really using another.
Noncompliant code example
class Foo
{
public:
void doSomething();
private:
int myField;
};
void Foo::doSomething()
{
int myField = 0; // Noncompliant
// ...
}
void f(int x, bool b) {
int y = 4;
if (b) {
int x = 7; // Noncompliant
int y = 9; // Noncompliant
// ...
}
}
Compliant solution
class Foo
{
public:
void doSomething();
private:
int myField;
};
void Foo::doSomething()
{
int myInternalField = 0; // Compliant
// ...
}
void f(int x, bool b) {
int y = 4;
if (b) {
int z = 7; // Better yet: Use meaningful names
int w = 9;
// ...
}
}
Exceptions
It is common in a constructor to have constructor arguments shadowing the fields that they will initialize. This pattern avoids the need to select
new names for the constructor arguments, and will not be reported by this rule:
class Point{
public:
Point(int x, int y) : x(x), y(y) {} // Compliant by exception
private:
int x;
int y;
};
Resources
- MISRA C:2004, 5.2 - Identifiers in an inner scope shall not use the same name as an identifier in an outer scope, and therefore hide that
identifier
- MISRA C++:2008, 2-10-2 - Identifiers declared in an inner scope shall not hide an identifier declared in an outer scope
- MISRA C:2012, 5.3 - An identifier declared in an inner scope shall not hide an identifier declared in an outer scope
- CERT, DCL01-C. - Do not reuse
variable names in subscopes
- CERT, DCL51-J. - Do
not shadow or obscure identifiers in subscopes