01 / 21

Avoiding Conditional
Bugs in C++

Master the art of writing correct conditionals by understanding ordering pitfalls, boundary conditions, and common logical traps.

C++

What Is a Conditional Bug?

A conditional bug occurs when your if/else logic does not match the behavior you intended. The code compiles and often runs without crashing, but it produces wrong results for certain inputs.

Why Conditionals Go Wrong

Ordering Errors
Checking conditions in the wrong sequence so a more general case shadows a specific one.
Boundary Mistakes
Using \( < \) when you need \( \leq \), or missing the exact edge value your logic must handle.
Logic Confusion
Mixing up \( && \) and \( || \), accidentally assigning with \( = \) instead of comparing with \( == \).

The Bug Lifecycle

Write Code Compiles OK Passes Most Tests Fails at Boundaries Silent conditional bugs survive until edge cases expose them

The Golden Rule of Conditionals

0 60 70 80 90 100 F D C B A ✓ Correct: most specific first
if (score \( \geq \) 90) grade = 'A';
else if (score \( \geq \) 80) grade = 'B';
else if (score \( \geq \) 70) grade = 'C';
else if (score \( \geq \) 60) grade = 'D';
else grade = 'F';
Each branch narrows the remaining range: no gaps, no overlaps

Ordering Matters: Shadowing

When a general condition appears before a specific one, the specific branch never executes. This is called shadowing.

✕ Bug: general first
if (score \( \geq \) 60) { grade = 'D'; // 95 lands here! } else if (score \( \geq \) 90) { grade = 'A'; // never reached }
✓ Fix: specific first
if (score \( \geq \) 90) { grade = 'A'; // 95 lands here } else if (score \( \geq \) 60) { grade = 'D'; // 65 lands here }

\( = \) vs \( == \) and \( < \) vs \( \leq \)

Bug Version Correct Version
Assignment vs Comparison if (x \( = \) 5) if (x \( == \) 5)
Off-by-one: excluding boundary if (i \( < \) n) when you need to include \( i = n \) if (i \( \leq \) n)
Off-by-one: including extra if (i \( \leq \) n) for 0-indexed array if (i \( < \) n)
Negation confusion if (\( !x > 0 \)) if (\( !(x > 0) \))

Boundary Conditions Visualized

Array of size 5 (indices 0 to 4) [0] [1] [2] [3] [4] [5] OUT OF BOUNDS
✕ Bug: \( i \leq 5 \)
for (int i = 0; i \( \leq \) 5; i++)
Accesses arr[5]: undefined behavior
✓ Fix: \( i < 5 \)
for (int i = 0; i \( < \) 5; i++)
Stops at arr[4]: correct last index

The \( && \) vs \( || \) Trap

Confusing AND with OR is one of the most frequent conditional bugs. De Morgan's Laws are your best friend:

✕ Bug
// "not between 1 and 10" if (x \( < \) 1 \( && \) x \( > \) 10) // always false!
✓ Fix
// "not between 1 and 10" if (x \( < \) 1 \( || \) x \( > \) 10) // correct range check

The 5-Step Checklist

1
List all branches. Write every possible outcome before coding any condition.
2
Order specific to general. Put the tightest condition first, the catch-all last.
3
Test boundaries. Plug in the exact boundary values: 0, \( n-1 \), \( n \), negative numbers, empty inputs.
4
Check operators. Verify every ==, <, <=, &&, || matches your intent.
5
Add an else clause. Ensure no input falls through without being handled.

Example 1: Range Check

Write a function that returns "child" for ages 0 to 12, "teen" for 13 to 17, and "adult" for 18 and above.

string ageGroup(int age) { if (age \( < \) 0) return "invalid"; // guard clause if (age \( \leq \) 12) return "child"; // 0-12 if (age \( \leq \) 17) return "teen"; // 13-17 return "adult"; // 18+ }

Example 2: Nested Condition Trap

A ticket system gives a discount to students or seniors. A common bug: nesting the check incorrectly.

✕ Bug: wrong nesting
if (isStudent) { if (age \( \geq \) 65) { applyDiscount(); // only } // student } // seniors!
✓ Fix: use ||
if (isStudent \( || \) age \( \geq \) 65) { applyDiscount(); // students } // OR seniors

Example 3: Short-Circuit Safety

C++ evaluates \( && \) left to right and stops early if the left side is false. You can use this to guard dangerous operations.

✕ Crash: no guard
if (arr[i] \( == \) target \( && \) i \( < \) n) { // arr[i] accessed BEFORE // checking i \( < \) n // crash if i \( \geq \) n }
✓ Fix: guard first
if (i \( < \) n \( && \) arr[i] \( == \) target) { // i \( < \) n checked FIRST // arr[i] only if i valid // safe access }

The Dangling Else Problem

Without braces, an else binds to the nearest if, not the one you might intend.

✕ Ambiguous
if (x \( > \) 0) if (x \( < \) 100) cout << "valid"; else cout << "negative"; // else binds to inner if! // "negative" prints when // x \( \geq \) 100, not x \( \leq \) 0
✓ Use braces
if (x \( > \) 0) { if (x \( < \) 100) { cout << "valid"; } } else { cout << "negative"; } // clear intent

Common Mistakes

✕ Assignment in Condition
Writing if (x = 5) instead of if (x == 5). Always assigns and evaluates as true.
✕ Off-by-One in Loops
Using \( \leq \) with array size causes out-of-bounds access. Arrays are 0-indexed: valid indices are 0 to \( n-1 \).
✕ Shadowed Branches
Placing a general check before a specific one. The specific branch becomes dead code that never executes.
✕ Missing Else
Forgetting the else fallback leaves inputs unhandled, causing undefined or stale variable values.

Quick Reference Table

Bug Type Symptom Prevention
Shadowing Specific branch never runs Order specific to general
Off-by-one Crash or missing last element Test at boundary values
\( = \) vs \( == \) Condition always true Enable compiler warnings
\( && \) vs \( || \) Impossible or always-true condition Apply De Morgan's Laws
Dangling else Else binds to wrong if Always use braces {}
Short-circuit order Crash on invalid access Guard check on the left

Question 1 of 5

What does the expression if (x = 10) do in C++?

Question 2 of 5

If score = 85, what grade is assigned?

Question 3 of 5

For an array of size \( n \), which loop condition correctly iterates over all valid indices?

Question 4 of 5

You want to check that x is not between 1 and 100 (inclusive). Which condition is correct?

Question 5 of 5

Why is it important that i < n appears before arr[i] == target?