Main Content

Variable shadowing

Variable hides another variable of same name with nested scope

Description

This defect occurs 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.

Polyspace® does not report a defect for variables with the name _ in structure bindings. Variables with this name are often placeholders.

Risk

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.

Fix

The fix depends on the root cause of the defect. For instance, suppose you refactor a function such that you use a local static variable in place of a global variable. In this case, the global variable is redundant and you can remove its declaration. Alternatively, if you are not sure if the global variable is used elsewhere, you can modify the name of the local static variable and all references within the function.

If the shadowing is intended and you do not want to fix the issue, add comments to your result or code to avoid another review. See

Examples

expand all

#include <stdio.h>

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

int factorial(int n)
 {
  int fact=1; 
  /*Defect: Local variable hides global array with same name */

  for(int i=1;i<=n;i++)
    fact*=i;

  return(fact);
 }

Inside the factorial function, the integer variable fact hides the global integer array fact.

Correction — Change Variable Name

One possible correction is to change the name of one of the variables, preferably the one with more local scope.

#include <stdio.h>

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

int factorial(int n)
 {
  /* Fix: Change name of local variable */
  int f=1; 

  for(int i=1;i<=n;i++)
    f*=i;

  return(f);
 }

Result Information

Group: Data flow
Language: C | C++
Default: On for handwritten code, off for generated code
Command-Line Syntax: VAR_SHADOWING
Impact: Low

Version History

Introduced in R2013b

expand all