Variables

2.4 - Default vs value initialization


In C++, if you create a new variable like this:

int x;

You might expect x to be 0, but actually it's going to be a garbage. A garbage is whatever value is left on the memory, so the value x can be anything unexpected, leading to bugs.

To ensure that your variable is initialized to 0, you can assign the value 0 immediately to it on the creation:

int x = 0;

Or you can use the curly brace initialization which ensures the value is 0:

int x{};