在循环中重新声明 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
头中的i
和int 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++
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"
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.
相关文章