user5378087
user5378087

Reputation:

Incomprehensible default initialization of POD

I read a lot here and in cppreference that automatic POD types isn't default initializated, but I tried to test some codes and I had some strange results. Look:

#include <iostream>

int main( ) {
    int x;
    std::cout << "x: " << x << std::endl;
    return 0;
}

It will output x some random value. But if I modify my code like this:

#include <iostream>

void f( ) { 
    int i;
    std::cout << "i: " << i << std::endl;
}

int main( ) {
    f( );
    int x;
    std::cout << "x: " << x << std::endl;   
    return 0;
}

I'll have the following output:

i: 0
x: 4200814

And if I modify the order of the function call f( ); for after the declaration of x and its output, both x and i will set to a random value. Another thing: if I declare another variable with no initialization after the declaration of x and its output, like int y;, y will output 0 too.

So, why that variable i and possibly all others variables declared in function f are 'initializated' to 0. Maybe a consequence of underfined behavior or indeterminate value?

Upvotes: 0

Views: 81

Answers (1)

R Sahu
R Sahu

Reputation: 206627

I read a lot here and in cppreference that automatic POD types isn't default initializated,

That is not correct. When an object is not explicitly initialized, it is default initialized. What it means to be default initialized changes based on the type.

From C++11 Standard:

8.5 Initializers

...

6 To default-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

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

— otherwise, no initialization is performed.

Hence no initialization is performed for x and i.


Maybe a consequence of underfined behavior or indeterminate value?

Yes. Using the values of uninitialized variables is cause for undefined behavior.

The values of i and x can be anything. Don't count on any specific pattern. Their values would most likely change when you recompile, when you change compiler options, change compiler.

Upvotes: 1

Related Questions