Error redeclaring a for loop variable within the loop(在循环中重新声明 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.
这篇关于在循环中重新声明 for 循环变量时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在循环中重新声明 for 循环变量时出错


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01