Main Content

MISRA C++:2023 Rule 6.4.1

A variable declared in an inner scope shall not hide a variable declared in an outer scope

Since R2024b

Description

Rule Definition

A variable declared in an inner scope shall not hide a variable declared in an outer scope.

Rationale

When two variables with the same name exist in an inner and outer scope, any reference to the variable name uses the variable in the inner scope. However, a developer or reviewer might incorrectly expect that the variable in the outer scope was used.

Polyspace Implementation

The rule checker reports a violation when a variable hides another variable of the same name in an outer scope.

For instance, if a local variable has the same name as a global variable, the local variable hides the global variable during its lifetime.

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

#include <stdio.h>

int fact[5]={1,2,6,24,120};

int factorial (int n)  {
    int fact=1;     // Noncompliant
    for(int i=1;i<=n;i++)
         fact*=i;
    return(fact);
 }


int factorial_fixed (int n)  {
    int f=1;       // Compliant
    for(int i=1;i<=n;i++)
        f*=i;
    return(f);
 }

The declaration of the integer variable fact in the function factorial() is noncompliant because it hides the global integer array fact.

The function factorial_fixed() fixes the issue by renaming the local variable.

Check Information

Group: Basic concepts
Category: Required

Version History

Introduced in R2024b