Get warning when a variable is shadowed

后端 未结 1 755
一整个雨季
一整个雨季 2020-11-28 15:25

I generally want to avoid code like this:

#include 

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

  int n = 3;

  for (int n = 1; n <= 10; n++){
             


        
相关标签:
1条回答
  • 2020-11-28 15:52

    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.

    0 讨论(0)
提交回复
热议问题