简体   繁体   English

什么是“变量'我没有在c ++中声明范围”?

[英]What is “ Variable ' i ' was not declared in scope ” in c++?

While practicing c++ code, I used the variable that was declared in the for loop.i want it to use it again in another for loop. 在练习c ++代码时,我使用了for循环中声明的变量。我希望它在另一个for循环中再次使用它。 But it showed me an error that the 但它向我展示了一个错误

variable i was not declared in scope

and I tried the same loop in Eclipse IDE it showed me 我在Eclipse IDE中尝试了相同的循环

the symbol i was not resolved . the symbol i was not resolved

The sample code looks similar to this: 示例代码看起来类似于:

 #include<iostream>

    using namespace std;

    int main(){
        for(int i=0;i<10;i++){
            cout<<i;
        }
        for(i=10;i<20;i++){
            cout<<i;
        }
    }

You have to declare the variable for each scope: 您必须为每个范围声明变量:

#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;
    }
}

After the first loop, there is no i anymore. 在第一个循环之后, i再也没有了。 You can try what the compiler says and see that this will fail: 您可以尝试编译器所说的内容,看看这会失败:

int main(){
    for(int i=0;i<10;i++){
        cout<<i;
    }
    cout<<i; // Error
}

i only defined within the scope of the first for loop, so it needs to be re-declared in the second one. i只在第一个for循环的范围内定义,所以它需要在第二个循环中重新声明。

Early Microsoft C++ compilers had a bug where the i leaked into the scope of the for loop to produce effectively 早期的Microsoft C ++编译器有一个错误, i泄漏到for循环的范围,以有效地生成

int i;
for (i = 0; i < 10; i++){

By writing for(int i=0; i<10; i++) {...} you declare the int i inside the for loop scope and it only has effect inside the for loop. 通过写入for(int i=0; i<10; i++) {...}你可以在for循环范围内声明int i ,它只在for循环中有效。

If you want to re-use the int i then you should place it outside of & before any for loop: 如果你想重新使用int i你应该把它放在for循环之前和之前:

#include<iostream>

using namespace std;

int main(){
    int i = 0;
    for(i=0; i<10; i++){
        cout<<i;
    }
    for(i=10; i<20; i++){
        cout<<i;
    }
    cout<<i; // <- fine, 20
}

Or, simply repeat the declaration with each for loop then int i in for loops are totally different variables. 或者,只需用每个for循环重复声明然后int i for in循环是完全不同的变量。

#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;
    }
    //cout<<i; <- oops!!! error
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM