Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get warning when a variable is shadowed

I generally want to avoid code like this:

#include <stdio.h>

int main(int argc, char *argv[]){

  int n = 3;

  for (int n = 1; n <= 10; n++){
    printf("%d\n", n);
  }

  printf("%d\n", n);
}

How can I find such usage of variables? That means, that in the same function a "more local" variable has the same name as a more global variable?

C-Standard : C 99

like image 569
Ystar Avatar asked Aug 06 '14 02:08

Ystar


People also ask

How do you avoid variable shadowing?

Variable shadowing could be avoided by simply renaming variables with unambiguous names. We could rewrite the previous examples: The inner scope has access to variables defined in the outer scope.

What is illegal shadowing in Javascript?

Illegal Shadowing: Now, while shadowing a variable, it should not cross the boundary of the scope, i.e. we can shadow var variable by let variable but cannot do the opposite.

What is the point of variable shadowing?

In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking.

What does shadowing a parameter mean?

However, somewhere in the function you want to declare a variable that has the same name as one of the function argument. Declaring a variable with a name that already refers to another variable is called shadowing.


1 Answers

Both gcc and clang support the -Wshadow flag which will warn about variables that shadow one another. For example the warning I receive from gcc for your code is the following:

warning: declaration of ‘n’ shadows a previous local [-Wshadow]
for (int n = 1; n <= 10; n++){
         ^
warning: shadowed declaration is here [-Wshadow]
int n = 3;
    ^

gcc documents the flag here and says:

Warn whenever a local variable or type declaration shadows another variable, parameter, type, class member (in C++), or instance variable (in Objective-C) or whenever a built-in function is shadowed. Note that in C++, the compiler warns if a local variable shadows an explicit typedef, but not if it shadows a struct/class/enum.

In Visual Studio this looks like it was not possible before but seems to be fixed in recent versions.

like image 130
Shafik Yaghmour Avatar answered Sep 19 '22 11:09

Shafik Yaghmour