Loading lessons...
Uninitialized Variables and Undefined Behavior
Uninitialized Variables and Undefined Behavior
A variable that we declare but never give a value is uninitialized. What does it actually contain? Surprise: we don't know.
The indeterminate value
When you write:
int x; // declared, never initialized
cout << x; // prints ... something unknown
The box x is not empty and it is not 0. It holds whatever bits happened to be in that memory before - often called a garbage value. The result can change from run to run, machine to machine.
Why is this bad?
Reading an uninitialized variable is undefined behavior. "Undefined behavior" is the worst phrase in C++: the language makes no promise at all about what happens. The program might:
- Print a garbage number.
- Seem to work by coincidence.
- Crash on another compiler, or behave differently tomorrow.
Undefined behavior is a bug, even if the program looks fine. Bugs that depend on "whatever was in memory" are the hardest to find.
Always initialize
The fix is embarrassingly simple - always give a variable a value when you create it:
int x { 0 }; // know exactly what's inside
int y { 5 }; // even a value you plan to replace
When is it really a problem?
Some variables are set before first use (like a loop counter assigned right away), so a quick read may be fine. But there is no way to know that for sure - and no cost to initializing. Make it a habit:
- Initialize every variable at creation.
- Never read a variable before it has a value.
TL;DR
- An uninitialized variable holds an indeterminate garbage value.
- Reading it is undefined behavior - the program's behaviour is unpredictable.
- It might work by luck, print junk, or crash; it's a bug regardless.
- Fix: always initialize, e.g.
int x { 0 };.