在循环中重新声明 for 循环变量时出错 [英] Error redeclaring a for loop variable within the loop

查看:49
本文介绍了在循环中重新声明 for 循环变量时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个 C 程序片段:

for(int i = 0; i <5; i++){国际我= 10;//<- 注意局部变量printf("%d", i);}

它编译没有任何错误,并且在执行时给出以下输出:

1010101010

但是如果我用 C++ 写一个类似的循环:

for(int i = 0; i <5; i++){国际我= 10;std::cout <<一世;}

编译失败并出现此错误:

prog.cc:7:13: 错误:'int i' 的重新声明国际我= 10;^prog.cc:5:13: 注意:'int i' 之前在这里声明过for(int i = 0; i <5; i++)^

为什么会这样?

解决方案

这是因为 C 和 C++ 语言对于在嵌套在 for 循环中的范围内重新声明变量有不同的规则:

  • C++i 放在循环体的作用域内,所以第二个int i = 10 是重声明,禁止莉>
  • C 允许在 for 循环内的范围内重新声明;最里面的变量获胜"

这是一个运行C程序的演示,以及一个C++ 程序无法编译.

在正文中打开嵌套范围修复了编译错误(demo):

for (int i =0 ; i != 5 ; i++) {{国际我= 10;cout<<我<<结束;}}

现在for头中的iint i = 10在不同的范围内,所以程序可以运行了.>

Consider this snippet of a C program:

for(int i = 0; i < 5; i++)
{
    int i = 10;  // <- Note the local variable

    printf("%d", i); 
}    

It compiles without any error and, when executed, it gives the following output:

1010101010

But if I write a similar loop in C++:

for(int i = 0; i < 5; i++)
{
     int i = 10;

     std::cout << i; 
}

The compilation fails with this error:

prog.cc:7:13: error: redeclaration of 'int i'  
     int i = 10;  
         ^  
prog.cc:5:13: note: 'int i' previously declared here  
     for(int i = 0; i < 5; i++)  
             ^   

Why is this happening?

解决方案

This is because C and C++ languages have different rules about re-declaring variables in a scope nested in a for loop:

  • C++ puts i in the scope of loop's body, so the second int i = 10 is a redeclaration, which is prohibited
  • C allows redeclaration in a scope within a for loop; innermost variable "wins"

Here is a demo of a running C program, and a C++ program failing to compile.

Opening a nested scope inside the body fixes the compile error (demo):

for (int i =0 ; i != 5 ; i++) {
    {
        int i = 10;
        cout << i << endl;
    }
}

Now i in the for header and int i = 10 are in different scopes, so the program is allowed to run.

这篇关于在循环中重新声明 for 循环变量时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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