Luchian Grigore
Luchian Grigore

Reputation: 258608

Is a local scoped variable initialized to an undetermined value, or un-initialized?

Pedantically speaking, is x initialized in the following code or not?

int main()
{
    int x;
}

There are some paragraphs about it in 8.5 Initializers [dcl.init] (for C++11) but not backed by any examples.

Upvotes: 2

Views: 109

Answers (3)

Columbo
Columbo

Reputation: 60979

No, it isn't. According to standard, x is default-initialized ([dcl.init]/6):

To default-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type [...]

— if T is an array type [...]

otherwise, no initialization was performed.

x is therefore uninitialized since no initialization is performed.
Hence the object has indeterminate value ([dcl.init]/11):

If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value.

Moreover, if we were to access it's stored, indeterminate value - in other words, perform an lvalue-to-rvalue conversion on it - we would induce undefined behavior ([conv.lval]/1]):

If the object to which the glvalue refers is [..], or if the object is uninitialized, a program that necessitates this conversion has undefined behavior.

Upvotes: 3

Abdulrahman Alhemeiri
Abdulrahman Alhemeiri

Reputation: 675

The way I understand it is that the place in memory for the variable x is reserved, but not set to a value (un-initialized). Because it is un-initialized, any old values there will be considered as 'garbage' int.

Upvotes: 2

dyp
dyp

Reputation: 39111

It is formally default-initialized, which means for ints, that no initialization is performed.

[dcl.init]/12 (N3797)

If no initializer is specified for an object, the object is default-initialized; if no initialization is performed, an object with automatic or dynamic storage duration has indeterminate value

[dcl.init]/7

To default-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type, the default constructor for T is called [...];

  • if T is an array type, each element is default-initialized;

  • otherwise, no initialization is performed.

Upvotes: 5

Related Questions