What happens when I print an uninitialized variable in C++?

That is because variables with automatic storage duration are not automatically initialized to zero in C++. In C++, you don’t pay for what you don’t need, and automatically initializing a variable takes time (setting to zero a memory location ultimately reduces to machine intruction(s) which are then translated to electrical signals that control the physical bits).

The variable is being reserved a memory location, and it happens that some junk is at that memory location. That junk is being printed out by cout.

As pointed out by @dwcanillas, it is undefined behaviour. Related: What happens to a declared, uninitialized variable in C? Does it have a value?

From the C++ standard (emphasize mine):

8.5 Initializers [dcl.init]

7) To default-initialize an object of type T means:

  • If T is a (possibly cv-qualified) class type (Clause 9), constructors are
    considered. The applicable constructors are enumerated (13.3.1.3), and the best
    one for the initializer () is chosen through overload resolution (13.3). The
    constructor thus selected is called, with an empty argument list, to initialize >> the object.
  • If T is an array type, each element is default-initialized.
  • Otherwise, no initialization is performed.

12) If no initializer is specified for an object, the object is default-initialized. When storage for an object with automatic or dynamic storage duration is obtained, the object has an indeterminate value, and if no initialization is performed for the object, that object retains an indeterminate value until that value is replaced (5.18). [Note: Objects with static or thread storage duration are zero-initialized, see 3.6.2. — end note ] If an indeterminate value is produced by an evaluation, the behavior is undefined except in the following cases:

— If an indeterminate value of unsigned narrow character type (3.9.1) is produced by the evaluation of:

— the second or third operand of a conditional expression (5.16),

— the right operand of a comma expression (5.19),

— the operand of a cast or conversion to an unsigned narrow character type (4.7, 5.2.3, 5.2.9, 5.4), or

— a discarded-value expression (Clause 5)

Leave a Comment