Main Content

MISRA C++:2008 Rule 2-10-2

Identifiers declared in an inner scope shall not hide an identifier declared in an outer scope

Description

Rule Definition

Identifiers declared in an inner scope shall not hide an identifier declared in an outer scope.

Rationale

The rule flags situations where the same identifier name is used in two variable declarations, one in an outer scope and the other in an inner scope.

int var; 
...
{
...
  int var;
...
}

All uses of the name in the inner scope refers to the variable declared in the inner scope. However, a developer or code reviewer can incorrectly assume that the usage refers to the variable declared in the outer scope.

Polyspace Implementation

The rule checker flags all cases of variable shadowing including when:

  • The same identifier name is used in an outer and inner named namespace.

  • The same name is used for a class data member and a variable outside the class.

  • The same name is used for a method in a base and derived class.

To exclude these cases, switch to the more modern standard AUTOSAR C++14 and check for the rule AUTOSAR C++14 Rule A2-10-1.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

int varInit = 1;

void doSomething(void);

void step(void) {
    int varInit = 0; //Noncompliant
    if(varInit)
       doSomething(); 
}

In this example, varInit defined in func hides the global variable varInit. The if condition refers to the local varInit and the block is unreachable, but you might expect otherwise.

void runSomeCheck(int);

void checkMatrix(int dim1, int dim2) {
  for(int index = 0; index < dim1; index++) {
      for(int index = 0; index < dim2; index++) { // Noncompliant
          runSomeCheck(index);
      }
  }
}

In this example, the variable index defined in the inner for loop hides the variable with the same name in the outer loop.

Check Information

Group: Lexical Conventions
Category: Required

Version History

Introduced in R2013b