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

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.

Leave a Comment