c++ - 在同一函数中定义变量及其静态等效项

标签 c++ c scope static shadowing

我不明白下面的代码是如何工作的:

#include "stdio.h"

int main(void) {
  int i = 3;
  while(i--) {
    static int i = 100;
    i--,
    printf("%d\n", i);
  }
  return 0;
}

使用 Clang 或 GCC 编译的代码会打印以下输出:

99
98
97

有人可以向我解释这里发生了什么吗?看起来两个操作是在一条指令中完成的,而且不止一次。它是未定义的行为吗? 我在 C++ 中观察到相同的行为。

最佳答案

这不是未定义的行为。

#include "stdio.h"

int main(void) {
  int i = 3; //first i
  while(i--) {
    static int i = 100; //second i
    i--,
    printf("%d\n", i);
  }
  return 0;
}

在 while 循环体中,大多数本地 i(第二个 i)是首选。在 while 循环中检查条件时,它不知道正文中有什么。所以选择第一个i是没有问题的。

关于c++ - 在同一函数中定义变量及其静态等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48539659/

相关文章:

c++ - 任何人都可以向我解释这个输出吗?

c++ - 在 AIR Native Extension 中包含库会导致错误,所有方法都为 "The extension context does not have a method with the name..."

javascript - $.proxy() 和 bind() 有什么区别?

c++ - 使用动态库时 undefined reference 问题

c++ - 使用 OpenCV 进行图像捕获 - 选择超时错误

c - 如何打印作为参数传递的特定内存地址?

c++ - 为什么动态绑定(bind)可以覆盖 C++ 中的名称隐藏?

c# - C#中如何使用全局变量?

c++ - Windows/C++ : Is it possible to find the line of code where exception was thrown having "Exception Offset"

c - 如何比较指针与ascii字符?