Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 480
cmuse Avatar asked Nov 23 '10 19:11

cmuse


People also ask

Why are uninitialized variables bad?

An uninitialized variable has an undefined value, often corresponding to the data that was already in the particular memory location that the variable is using. This can lead to errors that are very hard to detect since the variable's value is effectively random, different values cause different errors or none at all.

What happens if you print an uninitialized variable in Java?

This gives a compile time error stating that variable x might not have been initialized.

What happens when you try to use an uninitialized variable?

An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.

What is an uninitialized variable SET TO LET result What is result?

In computing, an uninitialized variable is a variable that is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. As such, it is a programming error and a common source of bugs in software.


1 Answers

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.

like image 181
GManNickG Avatar answered Sep 30 '22 15:09

GManNickG