include::../description.adoc[]

== 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;
};
----

== See

* 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 {cpp}: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
* https://wiki.sei.cmu.edu/confluence/display/c/DCL01-C.+Do+not+reuse+variable+names+in+subscopes[CERT, DCL01-C.] - Do not reuse variable names in subscopes
* https://wiki.sei.cmu.edu/confluence/display/java/DCL51-J.+Do+not+shadow+or+obscure+identifiers+in+subscopes[CERT, DCL51-J.] - Do not shadow or obscure identifiers in subscopes

ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]
