Get warning when a variable is shadowed

主宰稳场 提交于 2019-11-27 09:15:30

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.

I doubted this when I first saw it, so I had to see for myself, you're telling me you don't get these warnings right away?

This is assuming you're using gcc with no -std compiler flag (C90 mode).

rootavish@themachine /tmp $ gcc queer.c -oueer
queer.c: In function ‘main’:
queer.c:7:12: error: redefinition of ‘n’
   for (int n = 1; n <= 10; n++){
            ^
queer.c:5:7: note: previous definition of ‘n’ was here
   int n = 3;
       ^
queer.c:7:3: error: ‘for’ loop initial declarations are only allowed in C99 mode
   for (int n = 1; n <= 10; n++){
   ^
queer.c:7:3: note: use option -std=c99 or -std=gnu99 to compile your code

Might you specify your compiler flags?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!