Why isn\'t the output 101
while I assigned the previous x
to the new x
?
int x = 101;
{
int x = x;
std::cout &l
There's another way to do it.
#include <iostream>
int x = 101;
int main()
{
int x = ::x;
std::cout << x << std::endl;
std::cin.get();
}
variable scope In front of x will be overwritten. int x = x; This one there are two processes. One: int x;(define variable x and allocate memory and specify the initial value : x = 0); this moment , the front x will be hidden. Two: x = x;(Do not find the value x);
The point of declaration for a name is immediately after its complete declarator and before its initializer... [C++ Standard § 3.3.2/1]
Compiler completes the declaration when it knows enough about declarator.
Above code is equal to the below one:
int x = 101;
{
int x;
x = x; <------------------// Self assignment, assigns an indeterminate value.
std::cout << x << std::endl;
}
Because, the declaration of inner x
completed before =
(assignment)
int x = x; <--// Now, we have the new `x` which hides the older one,
^ // so it assigns itself to itself
|
+---// Point of declaration,
// here compiler knows everything to declare `x`.
// then declares it.
On the other hand, when we declaring complex objects, the point of declaration is farther. So, the behavior is different.
For example, below code is OK
const int i = 2;
{
int i[i];
^
|
+----// Point of declaration
// compiler has to reach to "]"
// therefore before declaring `i` as an array
// there is just one `i`, the `i` of `const int i=2`
}
In above code, compiler has to know the actual size of the array to complete the declaration, so the point of declaration is ]
. Therefore the i
within [i]
is the outer i
because declaration of the i
of int i[...
isn't completed yet. Thus, it declares an array with 2
elements (int i[2];
).
Also, this example shows the point of declaration for an enumerator
const int x = 12;
{
enum { x = x };
^
|
+---// Point of declaration
// compiler has to reach to "}" then
// there is just one `x`, the `x` of `const int x=12`
}
The enumerator x
is initialized with the value of the constant x
, namely 12
.