c - 当变量被隐藏时得到警告

标签 c variables warnings c99

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

#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/

相关文章:

c++ - VC++ 警告 C4356 : static data member cannot be initialized via derived class

c - 如何在 C 中复制字符串直到到达空格

c - log4c - 我怎样才能只看到信息消息?

C - 替换 64 位整数的第 n 个字节

javascript - JS 等于字符串中的值

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c++ - 如何将函数参数标记为输出

java - 为什么我的 Java for 循环不会在循环外设置变量?

php - 在 mysql 查询的 WHERE 子句中使用 php 变量

pcap_loop 的最后一个参数中的编译器警告。指向不同大小的整数