What is " Variable ' i ' was not declared in scope " in c++?

Viewed 2656

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. 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

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;
        }
    }
3 Answers

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. 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.

Early Microsoft C++ compilers had a bug where the i leaked into the scope of the for loop to produce effectively

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.

If you want to re-use the int i then you should place it outside of & before any for loop:

#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.

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