1.7 — Uninitialized variables

📘 Chapter 1⏱ about 1 min read✍️ Beginner friendly
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 anything
Undefined 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.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.