2

What is the value of y at the end of main?

const int x = 5;
int main(int argc, char** argv)
{
    int x[x];

    int y = sizeof(x) / sizeof(int);

    return 0;
}

y is 5

What is the value of the local variable x at the end of main?

int x = 5;
int main(int argc, char** argv)
{
    int x = x;
    return 0;
}

x is undefined

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
q0987
  • 34,938
  • 69
  • 242
  • 387
  • See [Does initialization entail lvalue-to-rvalue conversion? Is `int x = x;` UB?](http://stackoverflow.com/q/14935722/1708801) and [Has C++ standard changed with respect to the use of indeterminate values and undefined behavior in C++14?](http://stackoverflow.com/q/23415661/1708801) – Shafik Yaghmour Mar 12 '17 at 06:43
  • Also see [Variable and constant with same name](http://stackoverflow.com/q/29130530/1708801) – Shafik Yaghmour Mar 12 '17 at 06:43

1 Answers1

1

When declaring

int x[x];

the global x is used to define the size of array. The x in the [] is the global variable since the declaration of the local variable is not yet complete.

In the second case,

int x = x;

is undefined behavior since the x on the RHS is the same as the x on the LHS since the declaration of x is complete by the time x on the RHS is encountered.

These are described in the C++11 Standard:

3.3.2 Point of declaration

1 The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [ Example:

int x = 12;
{ int x = x; }

Here the second x is initialized with its own (indeterminate) value. — end example ]

2 Note: a name from an outer scope remains visible up to the point of declaration of the name that hides it.[ Example:

const int i = 2;  
{ int i[i]; }

declares a block-scope array of two integers. — end example ] — end note ]

R Sahu
  • 204,454
  • 14
  • 159
  • 270