NtscCobalt
NtscCobalt

Reputation: 1689

Initializing a shadowing variable

Is there anything in the standard that defines initialing a variable from the variable it shadows?

For example:

int i = 7;
{
    int i = i;
}

Visual Studio 2013 allows this without a warning and works as expected. The inner i variable is 7. Clang and GCC however give me a warning about a initializing variable initializing from itself will be uninitialized.

Upvotes: 3

Views: 662

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

If the first variable is defined in a namespace for example in the global namespace then you can write using its qualified name

int i = 7;

int main()
{
   int i = ::i;
   //...
}

Upvotes: 3

Igor Tandetnik
Igor Tandetnik

Reputation: 52591

The standard has this to say:

3.3.2 Point of declaration [basic.scope.pdecl]

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 ]

This is precisely your case. The program exhibits undefined behavior by way of accessing an uninitialized object.

My copy of VS2013 reports error C4700: uninitialized local variable 'i' used for this code. Not sure why your copy behaves differently.

Upvotes: 9

Related Questions