If...Else

If...Else in C++: A program without conditions is a train on a single track: same route, same destination, every time.

The Analogy: The Fork in the Road

A program without conditions is a train on a single track: same route, same destination, every time. An if statement is a set of points — a fork where the train can be switched onto a different line depending on a signal.

if / else if / else is a chain of forks tested in order. The train takes the first track whose signal is green and never looks at the rest. That "first match wins" behaviour is the whole design, and getting the order wrong is the most common logic bug in beginner code.


Syntax or Core Structure

#include <iostream>

int main() {
    int score{78};

    // Single fork
    if (score >= 50) {
        std::cout << "Pass\n";
    }

    // Two-way fork
    if (score >= 50) {
        std::cout << "Pass\n";
    } else {
        std::cout << "Fail\n";
    }

    // Chain -- first true branch wins, the rest are skipped
    if (score >= 90) {
        std::cout << "Grade A\n";
    } else if (score >= 75) {
        std::cout << "Grade B\n";     // this one runs
    } else if (score >= 60) {
        std::cout << "Grade C\n";
    } else {
        std::cout << "Grade F\n";
    }

    // Nested -- a fork inside a fork
    bool enrolled{true};
    if (enrolled) {
        if (score >= 50) {
            std::cout << "Certificate issued\n";
        } else {
            std::cout << "Resit required\n";
        }
    }

    return 0;
}

The condition must go in parentheses, and the body is a brace-delimited block. Braces are optional for a single statement, but leaving them out is how the famous Apple "goto fail" security bug happened — always write them.


Technical Depth: What Counts as True, and Where Order Bites

Any number is a condition

int count{3};
if (count) { }          // true -- any non-zero value
if (!count) { }         // true only when count == 0

int* ptr = nullptr;
if (ptr) { }            // false -- null pointer converts to false
if (!ptr) { }           // true

std::string s{""};
if (s) { }              // COMPILE ERROR -- strings do not convert to bool
if (!s.empty()) { }     // correct

Zero, nullptr and false are falsy; everything else is truthy. Unlike Python, an empty string or empty container is not falsy — you must call .empty(). Being explicit reads better anyway: if (count > 0) says more than if (count).

Order in a chain is not cosmetic

// BROKEN -- every passing score reports "Grade C"
if (score >= 50)      { std::cout << "Grade C\n"; }
else if (score >= 75) { std::cout << "Grade B\n"; }   // unreachable
else if (score >= 90) { std::cout << "Grade A\n"; }   // unreachable

Because the first true test wins, a chain of overlapping ranges must go from most restrictive to least. Nothing warns you here; the program simply gives wrong answers. Test the boundaries — 49, 50, 74, 75, 89, 90 — and the bug appears immediately.

The dangling else

if (a)
    if (b) doX();
else doY();          // Indentation LIES: this else belongs to if (b), not if (a)

An else always attaches to the nearest unmatched if, regardless of how you indent it. Braces make the intent unambiguous and impossible to misread.

Initialising inside the condition (C++17)

if (int remainder = total % 5; remainder != 0) {
    std::cout << "Not divisible, remainder " << remainder << "\n";
} else {
    std::cout << "Divisible\n";     // remainder is visible here too
}
// remainder is out of scope here -- it cannot leak or be reused by accident

The variable lives only inside the if and its else. This is the C++17 way to keep a temporary tightly scoped, and it pairs beautifully with functions that return a value plus a success flag.

Scope inside branches

if (score >= 50) {
    std::string message{"Passed"};      // born here
}
// std::cout << message;                // ERROR: died at the closing brace

Every block is a scope. A variable declared inside a branch does not exist outside it, so declare it before the if when both branches and the code after need it.

Guard clauses beat deep nesting

// Nested: hard to follow, and the real work is four levels deep
if (loggedIn) {
    if (hasSubscription) {
        if (!isBanned) {
            playVideo();
        }
    }
}

// Guard clauses: each failure exits early, the happy path stays flat
if (!loggedIn)        { return; }
if (!hasSubscription) { return; }
if (isBanned)         { return; }
playVideo();

Both versions do the same thing. The second one is easier to read, easier to extend, and each rejection can carry its own error message. Prefer it whenever you find yourself three if levels deep.


Real World Example: Ticket Pricing Rules

#include <iostream>
#include <string>

double ticketPrice(int age, bool isStudent, bool isWeekend) {
    // Guard clauses first: the special cases that override everything
    if (age < 0)  { return -1.0; }        // invalid input signal
    if (age < 3)  { return 0.0; }         // infants free

    double base{0.0};

    // Most restrictive band first -- order matters
    if (age < 16) {
        base = 6.50;                      // child
    } else if (age >= 65) {
        base = 7.00;                      // senior
    } else if (isStudent) {
        base = 8.00;                      // student
    } else {
        base = 12.00;                     // standard adult
    }

    if (isWeekend) {
        base += 2.00;                     // weekend surcharge for everyone
    }

    return base;
}

int main() {
    struct Case { int age; bool student; bool weekend; };
    const Case cases[]{ {2,false,false}, {10,false,true},
                        {20,true,false}, {30,false,true}, {70,false,false} };

    for (const Case& c : cases) {
        const double price = ticketPrice(c.age, c.student, c.weekend);

        std::cout << "Age " << c.age << ": ";
        if (price < 0.0) {
            std::cout << "invalid age\n";
        } else if (price == 0.0) {
            std::cout << "free\n";
        } else {
            std::cout << price << "\n";
        }
    }
    return 0;
}

The structure mirrors how the rules were probably written down. Invalid and free cases are guard clauses that leave immediately, so the rest of the function never has to think about them. The age bands are ordered most-restrictive-first, so a 10-year-old cannot accidentally fall through to the adult price. The weekend surcharge sits outside the chain because it applies to every band — putting it inside would mean repeating it four times.


Common Mistakes

  • Wrong order in a chain, so a later, stricter branch becomes unreachable. Always test boundary values.
  • = instead of ==. if (x = 5) assigns and is always true. Compile with -Wall.
  • Omitting braces for a one-line body, then adding a second line later that silently falls outside the if.
  • Chained comparisons like if (0 <= x <= 10). Compiles, always true. Use &&.
  • Expecting an empty string or zero-length container to be falsy. Use .empty().
  • Declaring a variable inside a branch and expecting to use it afterwards.
  • Comparing doubles with == in a condition. Use a tolerance.
  • A semicolon after the condition: if (x > 0); — the body becomes empty and the next line always runs.

Best Practices

  1. Always use braces, even for a single statement.
  2. Order chains from most specific to least specific, and always finish with an else so no case is silently ignored.
  3. Use guard clauses to flatten nesting; aim to never exceed two levels.
  4. Say what you mean: if (count > 0) rather than if (count).
  5. Scope temporaries with C++17 if (init; condition) so they cannot be reused by mistake.
  6. Extract a complicated condition into a named boolean: const bool eligible = age >= 18 && verified && !banned; then if (eligible).

Practice Exercises

  1. BMI classifier: Read height and weight, compute BMI, and print the category (underweight below 18.5, normal below 25, overweight below 30, obese otherwise). Verify each boundary value gives the category you expect.
  2. Refactor to guards: Take a function with three levels of nested if and rewrite it using early returns, giving each rejection its own message. Confirm the behaviour is identical.
  3. Triangle validator: Read three side lengths and print whether they form no triangle, an equilateral, an isosceles or a scalene triangle. Remember the rule that any two sides must sum to more than the third.