masoud
masoud

Reputation: 56479

Point of declaration in C++

Why isn't the output 101 while I assigned the previous x to the new x?

int x = 101;
{
    int x = x;
    std::cout << x << std::endl;
}

Output (garbage):

422634

I thought the second x would be initialized to 101 but it isn't initialized.

Note: The solution in this case is int x = ::x but the question is why it happens.

Upvotes: 33

Views: 2450

Answers (3)

chuang wang
chuang wang

Reputation: 65

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);

Upvotes: 0

masoud
masoud

Reputation: 56479

Point of declaration

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.

Upvotes: 47

greego
greego

Reputation: 105

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();
}

Upvotes: 9

Related Questions