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.
A variable should begin its life with a known value.
In C++, that is not automatic for every type. If you define a built-in local variable without an initializer, it may contain an indeterminate value.
Default-initialization is different to 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 << std::endl;
}
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.
The best habit is simple:
int count {};
double total {};
bool isValid {};
This gives each variable a known starting value.
Even better, initialize a variable with its intended value when possible:
int maxLives { 3 };
double taxRate { 0.10 };
bool isLoggedIn { false };