在循环中重新声明for循环变量时出错 [英] Error redeclaring a for loop variable within the loop
本文介绍了在循环中重新声明for循环变量时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下C程序片段:
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
但是,如果我在C ++中编写了类似的循环:
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++)
^
为什么会这样?
推荐答案
这是因为C和C ++语言对于在嵌套在for
循环中的作用域中重新声明变量具有不同的规则:
This is because C and C++ languages have different rules about re-declaring variables in a scope nested in a for
loop:
-
C++
将i
放在循环的主体范围内,因此第二个int i = 10
是重新声明,这是禁止的 -
C
允许在for
循环中的作用域中进行重新声明;最里面的变量"wins"
C++
putsi
in the scope of loop's body, so the secondint i = 10
is a redeclaration, which is prohibitedC
allows redeclaration in a scope within afor
loop; innermost variable "wins"
以下是正在运行的C程序和在主体内部打开嵌套作用域可修复编译错误(演示):
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;
}
}
现在for
标头中的i
和int i = 10
处于不同的作用域,因此允许运行该程序.
Now i
in the for
header and int i = 10
are in different scopes, so the program is allowed to run.
这篇关于在循环中重新声明for循环变量时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文