void main() {
int x=5;
{
int x= 6;
cout<<x;
}
cout<<x;
}
the output is 6, 5.
My question is: when Assign x to 6, it reserved a memory cell for it, and then entered the nested block here( the old x is destroyed!! Or how it can defined two variables for the same name?
The two
xin your example exists in different scopes. When you defined the innerx, it hides thexfrom outer scope. See the comments in the below given program.Also, the inner scope
xis destroyed when that scope ends. Moreover, the inner scopexand outer scopexoccupy different addresses in memory.The output of the above program is
65which can be seen here.Additionally, note that
void main()is not standard C++, you should instead replace it withint main()as shown in my above snippet.