問題描述
考慮這個 C 程序片段:
for(int i = 0; i <5; i++){國際我= 10;//<- 注意局部變量printf("%d", i);}
它編譯沒有任何錯誤,并且在執(zhí)行時給出以下輸出:
1010101010
但是如果我用 C++ 寫一個類似的循環(huán):
for(int i = 0; i <5; i++){國際我= 10;std::cout <<一世;}
編譯失敗并出現(xiàn)此錯誤:
prog.cc:7:13: 錯誤:'int i' 的重新聲明國際我= 10;^prog.cc:5:13: 注意:'int i' 之前在這里聲明過for(int i = 0; i <5; i++)^
為什么會這樣?
這是因為 C 和 C++ 語言對于在嵌套在 for
循環(huán)中的范圍內重新聲明變量有不同的規(guī)則:>
C++
把i
放在循環(huán)體的作用域內,所以第二個int i = 10
是重聲明,禁止莉>C
允許在for
循環(huán)內的范圍內重新聲明;最里面的變量獲勝"
這是一個運行C程序的演示,以及一個C++ 程序無法編譯.
在正文中打開嵌套范圍修復了編譯錯誤(demo):
for (int i =0 ; i != 5 ; i++) {{國際我= 10;cout<<我<<結束;}}
現(xiàn)在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.
這篇關于在循環(huán)中重新聲明 for 循環(huán)變量時出錯的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!