Lesson 67 +10 XP

Common If Statement Problems

Common If Statement Problems

LearnCpp 8.3 collects the mistakes that come up again and again when writing conditions.

= vs ==

The classic bug: one = assigns, two == compare.

int x = 5;
if (x = 5) // BUG: assigns, always true!
if (x == 5) // correct: compares

x = 5 stores 5 into x and returns it, which is always a truthy result. Use == to ask "is x equal to 5?".

Dangling else

An else pairs with the nearest unpaired if, which might surprise you when you nest. Braces make the pairing obvious instead of relying on whitespace.

if (a > 0)
  if (b > 0) cout << "both" << endl;
else
  cout << "a not positive" << endl; // no! this attaches to the inner if

Missing braces

Without braces, the if only wraps the single statement that follows it.

if (ready)
  cout << "go";       // this is inside the branch
  cout << "still here"; // always runs, even when not ready

Put braces around every branch so the block matches what you intend.

Comparing floating points

Computers store decimals approximately, so exact comparison fails:

double a = 0.1 + 0.2;
if (a == 0.3) // often false!

Compare with a tiny tolerance instead:

if (abs(a - 0.3) < 0.0001) // close enough

Range checks need &&

3 < x < 5 does not check a range the way it looks. C++ reads it left to right: first 3 < x becomes true (1) or false (0), then compares that result against 5. The result is usually not what you expect.

if (3 < x && x < 5) // correct way to check a range

TL;DR

  • Use == to compare, never = in a condition.
  • An else pairs with the nearest if; braces make the pairing obvious.
  • Without braces, an if wraps only the next single statement.
  • Never compare doubles directly; use a small tolerance.
  • Range checks need &&: write 3 < x && x < 5.