Main Content

AUTOSAR C++14 Rule A2-10-1

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

Description

Rule Definition

An identifier 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. In all cases flagged by this rule, you cannot clarify the usage further using the scope resolution operator.

Polyspace Implementation

The rule checker flags all cases of variable shadowing except 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.

The checker flags even those cases where the variable declaration in the outer scope occurs after the variable declaration in the inner scope. In those cases, though the variable hiding does not occur, reusing the variable name can cause developer confusion.

The rule does not flag these situations because you can clarify whether an usage of the variable refers to the variable in the inner or outer scope. For instance, in this example:

int var;

namespace n1 {
   int var;
}
within the namespace n1, you can refer to the variable in the inner scope as n1::var and the global variable as ::var.

The rule checker also does not detect these issues:

  • A variable in an unnamed namespace hides another variable in an outer scope.

  • A variable local to a lambda expression hides a captured variable.

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, Automated

Version History

Introduced in R2019a