Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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;
        }
    }
like image 236
Aadhish Avatar asked Dec 13 '22 13:12

Aadhish


2 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
}
like image 154
Matthieu Brucher Avatar answered Dec 25 '22 23:12

Matthieu Brucher


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++){
like image 21
Bathsheba Avatar answered Dec 25 '22 22:12

Bathsheba