Aad*_*ish 4 c++ variables scope
在练习c ++代码时,我使用了for循环中声明的变量.我希望它在另一个for循环中再次使用它.但它向我展示了一个错误
variable i was not declared in scope
我在Eclipse IDE中尝试了相同的循环
the symbol i was not resolved.
示例代码看起来类似于:
#include<iostream>
using namespace std;
int main(){
for(int i=0;i<10;i++){
cout<<i;
}
for(i=10;i<20;i++){
cout<<i;
}
}
Run Code Online (Sandbox Code Playgroud)
您必须为每个范围声明变量:
#include<iostream>
using namespace std;
int main(){
for(int i=0;i<10;i++){
cout<<i;
}
for(int i=10;i<20;i++){
cout<<i;
}
}
Run Code Online (Sandbox Code Playgroud)
在第一个循环之后,就没有i了.您可以尝试编译器所说的内容,看看这会失败:
int main(){
for(int i=0;i<10;i++){
cout<<i;
}
cout<<i; // Error
}
Run Code Online (Sandbox Code Playgroud)