考虑这个 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++ puts i in the scope of loop's body, so the second int i = 10 is a redeclaration, which is prohibitedC 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 循环变量时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
编译器如何处理编译时分支?What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
在 C/C++ 中检查空指针Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
比较运算符的数学式链接-如“if((5<j<=1))&quMath-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
“if constexpr()"之间的区别与“if()"Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++,'if' 表达式中的变量声明C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)