当变量被隐藏时收到警告 [英] Get warning when a variable is shadowed
问题描述
我通常想避免这样的代码:
#include int main(int argc, char *argv[]){整数 n = 3;for (int n = 1; n <= 10; n++){printf("%d
", n);}printf("%d
", n);}
如何找到变量的这种用法?这意味着,在同一个函数中,一个更局部"的变量与一个更全局的变量具有相同的名称?
C-标准:C 99
gcc 和 clang 都支持 -Wshadow
标志,它会警告变量相互影响.例如,我从 gcc
收到的警告如下:
warning: 'n' 的声明会影响之前的本地 [-Wshadow]for (int n = 1; n <= 10; n++){^警告:隐藏声明在这里 [-Wshadow]整数 n = 3;^
gcc
记录标志 此处 并说:><块引用>
每当局部变量或类型声明影响另一个时发出警告变量、参数、类型、类成员(在 C++ 中)或实例变量(在 Objective-C 中)或者当内置函数被隐藏时.笔记在 C++ 中,编译器会在局部变量隐藏显式 typedef,但如果它隐藏结构/类/枚举则不会.
在 Visual Studio 中,这看起来以前是不可能的,但是 似乎在最近的版本中已修复.
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);
}
printf("%d
", 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
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.
这篇关于当变量被隐藏时收到警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!