1.7 — Uninitialized variables
Read one box at a time. No rush.
Boxes full of junk#
If you make a variable without giving it a value, it may hold garbage: whatever was left in that memory before.
C++ — wrong ✗
int x; // no value given!std::cout << x; // could print 0, or 21857, or anythingUndefined behavior
When a program does something the rules do not allow — like using a variable that has no value — anything can happen. It might work, crash, or act strangely. This is called undefined behavior.
The easy fix#
Always give your variables a starting value.
C++ — right ✓
int x {}; // x is 0int y { 7 };Good habit
Always initialize your variables. It is one of the easiest ways to avoid strange bugs.
Tip: press ← / → to move between lessons, / to search.