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;
}
}
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++){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With