Thuta Learning
C++
BasicProgrammingBeginner

If...Else

C++Lesson 930 min

What you'll walk away with

  • Trace an if / else if / else chain and predict which single branch runs
  • Order overlapping range conditions so every branch is reachable
  • Combine conditions with &&, || and ! and write range checks correctly
  • Use C++17's if with an initializer and the ?: operator where they fit

Explain it simply

Explain it simply

Programs constantly need to choose. Is the password correct? Did the student pass? Is the item in stock? An if statement asks one yes-or-no question and runs a block of code only when the answer is yes. Add else and you get a second block for the no case, so exactly one of the two runs.

When there are more than two outcomes, such as Excellent, Pass or Fail, you chain the questions with else if. C++ asks them in order from the top and stops at the first yes. That one rule, the first true condition wins, explains almost every surprise beginners meet with if statements.

Problem → Why → Solution

The problem: an Excellent grade nobody can get

A teacher asks for a grading program: 80 or more is Excellent, 40 or more is Pass, anything lower is Fail. The first version checks mark >= 40 first, because 40 is the pass mark everyone talks about. A student with 95 opens the result page and sees Pass. Nothing crashes and no warning appears; the Excellent branch simply never runs, for any mark at all.

grade_bug.cpp
#include <iostream>

int main() {
    int mark = 95;

    if (mark >= 40) {
        std::cout << "Pass\n";        // 95 stops here
    } else if (mark >= 80) {
        std::cout << "Excellent\n";   // unreachable: 80+ is also 40+
    } else {
        std::cout << "Fail\n";
    }
    return 0;
}

Why does the Excellent branch never run?

An else if chain is not a set of independent rules. C++ tests a condition only if every condition above it was false, and it stops at the first one that is true. Every mark of 80 or more is also 40 or more, so the first test swallows them all. When ranges overlap, put the most specific, narrowest test first: mark >= 80, then mark >= 40, then else.

Core concept: the first true branch wins

An if statement evaluates its condition, converts the result to bool, and runs the following block only when that bool is true. The condition can be any expression that converts to bool: a comparison such as stock > 0, a bool variable, or even a number, where 0 counts as false and every other value as true. The optional else block runs when the condition is false, so an if-else pair always runs exactly one of its two blocks.

An else if chain is really an if nested inside the previous else. C++ walks down the chain, testing one condition after another, and runs the block of the first condition that is true. The remaining conditions are not even evaluated. If none is true, the final else runs; if there is no final else, nothing runs at all. This is why the order of overlapping conditions matters, and why the last else is the natural home for the "everything else" case.

Each block opens a new scope. A variable declared inside the braces of an if exists only until the closing brace, which keeps temporary values from leaking into the rest of the function. C++17 adds a way to scope a variable to the whole decision: if (auto pos = text.find('@'); pos != std::string::npos) declares pos and then tests it, and pos is visible in the if block and in every else block of the same statement, but not after it.

Conditions are combined with the logical operators from the operators lesson: && when both must hold, || when either is enough, and ! to negate. A range check must be written as two comparisons joined by &&, as in mark >= 0 && mark <= 100. For choosing between two values rather than two actions, the conditional operator is shorter: std::string result = mark >= 40 ? "Pass" : "Fail";.

Mental model: how a chain decides
  1. Test the first condition
  2. True? Run its block and leave the chain
  3. False? Move to the next else if
  4. Nothing true? Run else (if present)

Exactly one branch of a chain runs, or none if there is no else, and the later conditions are never even evaluated.

General pattern

cpp
if (condition) {
    // runs when condition is true
} else if (otherCondition) {
    // runs when only otherCondition is true
} else {
    // runs when nothing above was true
}

if (auto value = compute(); value > limit) { /* value is in scope */ }

auto choice = condition ? valueIfTrue : valueIfFalse;

Both else if and else are optional. In the initializer form (C++17) the part before the semicolon is a declaration and the part after it is the condition. ?: is an expression that yields one of two values depending on a condition.

Example: grading with a correctly ordered chain

Here the chain is ordered from the highest band down. With mark set to 75, follow the conditions yourself before reading the breakdown, and then try 80, 40 and 39 in your head to check the edges of each band.

cpp
#include <iostream>
using namespace std;

int main() {
    int mark = 75;

    if (mark >= 80) {
        cout << "Excellent";
    } else if (mark >= 40) {
        cout << "Pass";
    } else {
        cout << "Fail";
    }
    return 0;
}

Code breakdown

  1. Highest band firstif (mark >= 80) {

    75 >= 80 is false, so the Excellent block is skipped and C++ moves on to the next condition. Testing the narrowest band first is what makes every branch reachable.

  2. Next band} else if (mark >= 40) {

    This condition is only evaluated because the previous one was false. 75 >= 40 is true, so this block runs and the rest of the chain is skipped.

  3. The chosen outputcout << "Pass";

    The program prints Pass. The output has no newline because the code sends none; adding << '\n' (or endl) keeps the terminal prompt on its own line.

  4. Fallback} else {

    else has no condition: it catches every mark below 40, including negative numbers. A real program would reject impossible marks before this chain, as the deeper section shows.

You should see
Pass
How the grading chain decides
  1. Read mark
  2. mark >= 80?
  3. mark >= 40?
  4. else

75: first true test is mark >= 40

Pass

95: mark >= 80 is true

Excellent

25: no test is true

Fail

Guard clauses: reject bad input first

Real data contains surprises: a mark of 150 from a typo, or -1 meaning "absent". Check for impossible values at the top of the chain, so that the remaining branches can assume a valid mark. This snippet also uses || to catch both ends of the invalid range in a single test.

grade_guard.cpp
#include <iostream>

int main() {
    int mark = 150;

    if (mark < 0 || mark > 100) {
        std::cout << "Invalid mark: " << mark << '\n';
    } else if (mark >= 80) {
        std::cout << "Excellent\n";
    } else if (mark >= 40) {
        std::cout << "Pass\n";
    } else {
        std::cout << "Fail\n";
    }
    return 0;
}

if with an initializer, and the ?: operator

C++17 lets an if start with a declaration, followed by a semicolon and then the condition. The variable lives exactly as long as the decision, so it cannot be misused later in the function. The conditional operator ?: then picks one of two values in a single expression, which is handy for labels and messages.

setting.cpp
#include <iostream>
#include <string>

int main() {
    std::string setting = "theme=dark";

    if (auto eq = setting.find('='); eq != std::string::npos) {
        std::cout << "Key: " << setting.substr(0, eq) << '\n';
        std::cout << "Value: " << setting.substr(eq + 1) << '\n';
    } else {
        std::cout << "Not a key=value line\n";
    }
    // eq does not exist here any more

    int stock = 0;
    std::string label = stock > 0 ? "In stock" : "Sold out";
    std::cout << label << '\n';
    return 0;
}

In real projects

Where this shows up in real projects

Every request a server handles passes through chains of decisions before any real work starts: is the user logged in, are they allowed to see this page, is the input valid, is the item still available? Well-structured code handles the failure cases first with short guard clauses that return early, so the main logic below them reads straight down without deep nesting.

Business rules are often exactly the tiered chains from this lesson: shipping fees by weight band, tax brackets by income, discount levels by order total, or alert levels by sensor temperature. Because these rules change, teams keep the thresholds in named constants (or configuration) instead of scattering magic numbers like 80 and 40 through the code. They also write tests for each boundary value, such as 79, 80 and 81, because tiered logic usually breaks at the edges through off-by-one mistakes.

Common mistakes

Common mistakes

1. Writing a range like maths: 0 <= mark <= 100

C++ reads it as (0 <= mark) <= 100. The left part is a bool, 0 or 1, which is always <= 100, so the condition is true even for 150. g++ -Wall warns: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]. Write mark >= 0 && mark <= 100.

2. A semicolon right after the condition

if (mark >= 40); ends the if statement with an empty body, and the block below it runs every time. g++ -Wextra reports suggest braces around empty body in an 'if' statement [-Wempty-body]. Never put a semicolon between ) and {.

3. Leaving out the braces

Without braces, only the first statement belongs to the if. if (mark > 100) std::cout << "Too high\n"; mark = 100; resets every mark to 100, because the second statement runs unconditionally. GCC flags this with -Wmisleading-indentation; always use braces, even for a single line.

Best practices

Best practices

  • Order overlapping conditions from the most specific to the most general, and finish with an else that handles everything left.
  • Reject invalid input first so the remaining branches can trust their data.
  • Always use braces, and use if with an initializer when a helper variable is only needed for the decision.
  • Test the boundary values of every range, for example 39, 40, 79 and 80.

Mini challenge

Mini challenge: cinema ticket price

A cinema prices tickets by age and gives members a discount. Write the decision logic for one customer, then change the inputs and re-run to test every branch.

  • Reject an age below 0 or above 120 with an Invalid age message
  • Children under 5 are free, under 13 pay 2500 Ks, 60 and over pay 3000 Ks, everyone else pays 5000 Ks
  • Members get 500 Ks off any ticket that is not free
  • Use the ?: operator to print "member" or "guest" in the receipt line
ticket.cpp
#include <iostream>
#include <string>

int main() {
    int age = 67;
    bool isMember = true;
    int price = 0;

    // TODO: reject impossible ages first (below 0 or above 120)
    // TODO: choose the base price with an if / else if / else chain
    // TODO: apply the member discount, but never to a free ticket
    // TODO: print "Price for member, age 67: 2500 Ks" using ?: for member/guest
    return 0;
}

Expected: With age = 67 and isMember = true the output is: Price for member, age 67: 2500 Ks Also try age 3 (0 Ks), 10 (2000 Ks for a member), 30 (4500 Ks) and 130 (Invalid age: 130).

Show hint

In the invalid-age branch, print the message and leave main early with return 1; a non-zero exit code tells the shell something went wrong. Putting the under-13 test before the 60-and-over test keeps the ranges from overlapping. For the discount, test isMember && price > 0.

Show solution
ticket.cpp
#include <iostream>
#include <string>

int main() {
    int age = 67;
    bool isMember = true;
    int price = 0;

    if (age < 0 || age > 120) {
        std::cout << "Invalid age: " << age << '\n';
        return 1;
    }

    if (age < 5) {
        price = 0;
    } else if (age < 13) {
        price = 2500;
    } else if (age >= 60) {
        price = 3000;
    } else {
        price = 5000;
    }

    if (isMember && price > 0) {
        price -= 500;
    }

    std::string who = isMember ? "member" : "guest";
    std::cout << "Price for " << who << ", age " << age << ": " << price << " Ks\n";
    return 0;
}

Quick quiz 1 / 3

What does this print? int t = 31; if (t > 35) std::cout << "Hot"; else if (t > 25) std::cout << "Warm"; else if (t > 30) std::cout << "Very warm"; else std::cout << "Cool";

Quick quiz 2 / 3

With int mark = 150;, what does if (0 <= mark <= 100) do?

Quick quiz 3 / 3

In if (auto n = name.size(); n > 10) { ... } else { ... }, where can you use n?

What to remember

  • if runs its block only when the condition converts to true, and else covers the false case.
  • An else if chain runs only the first true branch, so order overlapping ranges from narrowest to widest.
  • Write ranges as two comparisons joined by &&, never as 0 <= x <= 100.
  • Always use braces, and never put a semicolon right after the condition.
  • if (init; condition) scopes a helper variable to the decision, and ?: chooses between two values.

The Current ISO C++ Standard (C++23) — Standard C++ Foundation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

If...Else | Thuta Learning