The following while loop does not terminate. This is because the variable x
is being re-declared inside the while loop. But I don't understand why in the second iteration onward, the statements x<10
and y=x
considers the x defined in the outer scope and not the x
defined in the block scope in the following statement.
Is this because once the first iteration ends, the x
defined in the block scope is destroyed and the loop begins to execute fresh?
#include<iostream>
int main () {
int x = 0, y;
while(x <10 ){
y = x;
std::cout<<"y is :"<< y <<std::endl;
int x = y + 1;
std::cout<<"x is :"<< x <<std::endl;
}
std::cout<<"While loop is over"<<std::endl;
}
Every iteration the while loop evaluates the outer scope x
and y
is assigned the value of the outer scope x
. After that another x
is defined in the inner scope which is what the second std::cout
uses, but the program makes no other use of the inner x
In the code below I replaced the inner x
with z
but otherwise the behavior is identical. The only difference is that there is not a second x
within a more inner scope to hide the outer one:
#include<iostream>
int main () {
int x = 0, y;
while(x <10 ){
y = x;
std::cout<<"y is :"<< y <<std::endl;
int z = y + 1;
std::cout<<"z is :"<< z <<std::endl;
}
std::cout<<"While loop is over"<<std::endl;
}
Below I have an example that is intended to clear the confusion. In the inner scope x
is not being "re-declared", a new x
is being declared and it goes out of scope after the }
:
#include<iostream>
int main () {
int x = 1;
{
int x = 2;
std::cout << x << '\n'; // 2
}
std::cout << x << '\n'; // 1
}