Using an uninitialized local variable

suggest change
int a;
std::cout << a; // Undefined behavior!

This results in undefined behavior, because a is uninitialised.

It is often, incorrectly, claimed that this is because the value is “indeterminate”, or “whatever value was in that memory location before”. However, it is the act of accessing the value of a in the above example that gives undefined behavior. In practice, printing a “garbage value” is a common symptom in this case, but that is only one possible form of undefined behavior.

Although highly unlikely in practice (since it is reliant on specific hardware support) the compiler could equally well electrocute the programmer when the program is run. With such a compiler and hardware support, such a response to undefined behavior would markedly increase average (living) programmer understanding of the true meaning of undefined behavior - which is that the standard places no constraint on the resultant behavior.

Using an indeterminate value of unsigned char type does not produce undefined behavior if the value is used as:

or if the value is discarded. In such cases, the indeterminate value simply propagates to the result of the expression, if applicable.

Note that a static variable is always zero-initialized (if possible):

static int a;
std::cout << a; // Defined behavior, 'a' is 0

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents