4.4 — Common if mistakes

📘 Chapter 4⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

1. Using = instead of ==#

C++ — wrong ✗
if (lives = 0)   // sets lives to 0! never true
C++ — right ✓
if (lives == 0)

2. A semicolon after the if#

C++ — wrong ✗
if (isHungry);{    std::cout << "Eat a snack\n";   // ALWAYS runs!}

The ; ends the if right away. The { } block then runs no matter what.

3. Missing braces#

C++ — wrong ✗
if (isRaining)    std::cout << "Take umbrella\n";    std::cout << "Wear boots\n";     // always runs, despite the indent!

Without { }, only one statement belongs to the if. The indent lies.

C++ — right ✓
if (isRaining){    std::cout << "Take umbrella\n";    std::cout << "Wear boots\n";}

4. Chained comparisons#

C++ — wrong ✗
if (1 <= x <= 10)
C++ — right ✓
if (x >= 1 && x <= 10)

5. Comparing decimals with ==#

C++ — wrong ✗
if (0.1 + 0.2 == 0.3)   // false!

Decimals are not exact (see 2.3 — Decimal numbers (double)). Check if they are close enough instead:

C++ — right ✓
if (std::abs((0.1 + 0.2) - 0.3) < 0.000001)   // needs <cmath>
Finished reading? Tick it off. Your progress is saved in this browser.

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