The standard stipulates that accessing the value of an uninitialised variable of automatic storage duration gives undefined behaviour.
The consequence is that any operation which relies on accessing the value gives undefined behaviour. Accessing the value of a variable is necessary to;
- Compare it with another value. For example,
a == b
gives undefined behaviour if either a
or b
is uninitialised. Even the comparison a == a
gives undefined behaviour if a
is uninitialised.
- Assign the value to another variable. For example,
a = b
gives undefined behaviour if b
is uninitialised.
- Pass it to a function by value. For a function
f()
, the call f(a)
will give undefined behaviour if a
is uninitialised.
- Output the value. For example,
std::cout << a
gives undefined behaviour if a
is uninitialised.
Because of this, there is no point in requiring an uninitialised variable to have a particular value. Accessing the value gives undefined behaviour, so testing if it is equal (or not equal, or greater than, or ....) to any value gives undefined behaviour.
This is often summarised by describing the value of an uninitialised variable as indeterminate. If it is not possible to access a value without introducing undefined behaviour, it is not possible to reliably determine what the value is.
Of course, there is then the question of why the standard deems that accessing the value of an uninitialised variable gives undefined behaviour. Leaving the value uninitialised allows the compiler to allocate memory for the variable (e.g. from stack) but not bother initialising it - the data in that memory can be whatever happens to be there. Initialising a variable to any specified value can be an expensive operation (e.g. an array of two million elements is a variable, albeit a big one, and initialising it may be computationally expensive). It is also often an unnecessary operation, since the first thing a lot of code does to an initialised variable is (wait for it ....) to assign a value to it i.e. to initialise it.
An operation that is (potentially) both unnecessary and computationally wasteful tends to be unpopular with both programmers and compiler vendors. Making the behaviour undefined does away with all of that .... albeit by requiring programmers to be careful to initialise their variables before any operation that accesses their values.