Why do I see strange values when I print uninitialized variables?

cmuse picture cmuse · Nov 23, 2010 · Viewed 8.3k times · Source

In the following code, the variable has no initial value and printed this variable.

int var;
cout << var << endl;

output : 2514932

double var;
cout << var << endl;

output : 1.23769e-307

I don't understand these output numbers. Can any one explain this to me?

Answer

GManNickG picture GManNickG · Nov 23, 2010

Put simply, var is not initialized and reading an uninitialized variable leads to undefined behavior.

So don't do it. The moment you do, your program is no longer guaranteed to do anything you say.


Formally, "reading" a value means performing an lvalue-to-rvalue conversion on it. And §4.1 states "...if the object is uninitialized, a program that necessitates this conversion has undefined behavior."

Pragmatically, that just means the value is garbage (after all, it's easy to see reading an int, for example, just gets random bits), but we can't conclude this, or you'd be defining undefined behavior.

For a real example, consider:

#include <iostream>

const char* test()
{
    bool b; // uninitialized

    switch (b) // undefined behavior!
    {
    case false:
        return "false";      // garbage was zero (zero is false)
    case true: 
        return "true";       // garbage was non-zero (non-zero is true)
    default:
        return "impossible"; // options are exhausted, this must be impossible...
    }
}

int main()
{
    std::cout << test() << std::endl;
}

Naïvely, one would conclude (via the reasoning in the comments) that this should never print "impossible"; but with undefined behavior, anything is possible. Compile it with g++ -02.