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++putsiin the scope of loop's body, so the secondint i = 10is a redeclaration, which is prohibitedCallows redeclaration in a scope within aforloop; 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 循环变量时出错
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
