C ++中for循环迭代语句的范围变量

时间:2012-07-11 04:52:10

标签: c++ scope language-lawyer specifications

根据我对C ++规范的理解(根据在线标准草案),可以根据while循环和初始化块重写for循环。根据我的理解,for循环的迭代语句发生在与body相同的范围内,因此它应该能够使用for循环体中声明的变量。 gcc和clang都拒绝以下(人为的)代码,这是我真实代码的简化。

我显然可以通过在循环外声明j来修复代码,但为什么j超出范围?

int main() 
{
    for(int i=0; i<10; i=j) int j=i+1;

    // // I must misunderstand the standard because I thought the above loop is 
    // // equivalent to the commented code below where j is clearly in scope.
    // {
    //     int i=0;
    //     while(i<10) {
    //         int j=i+1;
    //         i=j;
    //     }
    // }

    return 0;
 }

根据clang(和gcc),这是无效的。

test.cpp:3:26: error: use of undeclared identifier 'j'
    for(int i=0; i<10; i=j) int j=i+1;
                         ^
1 error generated.

4 个答案:

答案 0 :(得分:3)

for(int i=0; i<10; i=j) int j=i+1;

如果是有效语法,则与

相同
for(int i=0; i<10; i=j) 
{
  int j=i+1;
}
然后,for循环访问{}范围内的“j”,该范围在执行第一个循环之前不存在。 C ++是一种静态语言,它依赖于编译器能够在编译时解析其变量,但您正在尝试使其在运行时解析变量。

答案 1 :(得分:1)

作为参考,扩展如下(§6.5.3/ 1)。 for循环语句:

for (init cond; expr) statement

相当于:

{
    init
    while (cond)
    {
        statement
        expr;
    }
}

答案 2 :(得分:0)

这显然是显而易见的。我给你举个例子。你能写这样的东西吗?

int main(){
int i = j * 10;
//Some other lines ...
int j = 2;
return 0;
}

当然在给定的代码中,i和j在相同的范围内,但在使用j之前你必须声明它。
除了范围之外,你还必须考虑其他事情。

答案 3 :(得分:0)

你得到错误的原因是因为'j'在for循环中声明/初始化。但是在C ++编译器中,从左到右,从上到下进行编译,所以当编译器遇到“i”被赋予垃圾值时,会弹出错误。

相关问题