我通常想避免这样的代码:
#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);
}
如何找到变量的这种用法?这意味着,在同一个函数中,“更局部”的变量与更全局的变量具有相同的名称?
C-标准:C 99
最佳答案
gcc 和 clang 都支持 -Wshadow
标志,该标志将警告相互遮蔽的变量。例如,我从 gcc
收到的针对您的代码的警告如下:
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
记录标志 here并说:
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.
在 Visual Studio 中这看起来以前是不可能的,但是 seems to be fixed in recent versions .
关于c - 当变量被隐藏时得到警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25151524/