#013 – Avoid default initialization for variables

Consider the following

int x;

This is default-initialization. This defines the variable with a garbage value (not zero). If we print its contents, it will be whatever value is sitting at that memory address. Who knows!

When you don’t initialize a variable, C++ populates it with whatever contents that memory address holds. These are called garbage values.

This form of initialization is inherited from C back when computers were slow and gas was 50 cents a gallon.

Don’t confuse this with value-initialization

This is different than int myArray[10] {}; This performs value-initialization. The 10 elements are initialized with zero.

No garbage values.

This works on other types:

int x {};          // Initializes to 0
std::string name;  // name is "" (class types self-initialize)

Undefined behaviour

Some compilers produce an error for uninitialized variables. For example in this program, GCC produces this warning → 8 | int x; // Allocation without initialization

#include <iostream>

int main() {
    int x; // Defined only

    // Let's read it
    std::cout << "The value of x is: " << x << '\n';
}

When I run it, I receive this random result

The value of x is: 32758

Ultimately…

Since we’re professionals, avoid undefined behaviour at all costs.

Always initialize your built-in types.

Leave a Reply

Your email address will not be published. Required fields are marked *