how it can defined two variables for the same name?
The two x
in your example exists in different scopes. When you defined the inner x
, it hides the x
from outer scope. See the comments in the below given program.
int main()
{//---------------------------->scope1 started here
//------v---------------------->this variable x is in scope1
int x=5;
{//------------------------>scope2 started here
//----------v------------------>this variable x is in scope2
int x= 6;
//------------v---------------->this prints scope2's x value
cout<<x;
}//------------------------>scope2 ends here and x from scope2 is destroyed
//--------v---------------->this prints scope1's x value
cout<<x;
}//---------------->scope1 ends here
Also, the inner scope x
is destroyed when that scope ends. Moreover, the inner scope x
and outer scope x
occupy different addresses in memory.
The output of the above program is 65
which can be seen here.
Additionally, note that void main()
is not standard C++, you should instead replace it with int main()
as shown in my above snippet.