for循环外的变量范围 [英] scope of variable outside for loop

查看:39
本文介绍了for循环外的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用几年前编写并在以前版本的 MS VC++ 中编译的程序(我使用的是 VC++ 2008).有很多(数百个)类似于以下的实例:

I'm trying to use a program written a few years ago and compiled in a previous version of MS VC++ (I am using VC++ 2008). There are a lot (hundreds) of instances similar to the following:

int main () {
  int number = 0;
  int number2 = 0;

  for (int i = 0; i<10; i++) {
   //something using i
  }

  for (i=0; i<10; i++) {
   //something using i
  }

  return 0;
}

我不确定它最初是在哪个版本中编译的,但它有效.我的问题是:它是如何工作的?我的理解是 i 变量应该只定义为在第一个循环中使用.当我现在尝试编译它时,我收到了开始第二个循环的行的错误'i':未声明的标识符",这是有道理的.这在以前版本的 VC++ 中是否被忽略了?谢谢!

I'm not sure which version it was originally compiled in, but it worked. My question is: how did it work? My understanding is that the i variable should only be defined for use in the first loop. When I try to compile it now I get the error "'i': undeclared identifier" for the line starting the second loop, which makes sense. Was this just overlooked in previous versions of VC++? Thanks!

推荐答案

早期版本的 MSVC 有这个错误特征",因为它将这些变量泄漏到封闭的作用域中.

An earlier version of MSVC had this "misfeature" in that it leaked those variables into the enclosing scope.

换句话说,它处理了:

for (int i = 0; i<10; i++) {
    // something using i
}

同:

int i;
for (i = 0; i<10; i++) {
    // something using i
}

查看这个的答案问题我询问了一个奇怪的宏定义,了解更多细节.

See the answers to this question I asked about a strange macro definition, for more detail.

这篇关于for循环外的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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