当变量被遮盖时得到警告 [英] Get warning when a variable is shadowed

查看:523
本文介绍了当变量被遮盖时得到警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常想避免这样的代码:

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

C-Standard : C 99

推荐答案

gcc和clang都支持 -Wshadow 标志,该标志将警告那些隐藏了一个的变量另一个。例如,我从 gcc 收到的关于您的代码的警告如下:

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 记录了在此处标记并说:


每当局部变量或类型声明遮盖另一个
变量,参数,类型,类成员(在C ++中)或实例变量
(在Objective-C中)或当内置功能被遮盖。请注意
,在C ++中,编译器会在局部变量遮盖
显式typedef时发出警告,但在遮盖struct / class / enum时不会发出警告。

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中,这似乎以前是不可能的,但是

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

这篇关于当变量被遮盖时得到警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆