Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 171 ยท Control Flow

if, else if and else

Learn C++ if, else if and else - how conditions convert to bool, else-if chains, nesting and guard clauses, if with an initializer (C++17), if constexpr and common bugs.

So far your programs have run every statement from top to bottom. Real programs need to make decisions: reject a password that is too short, charge shipping only below a certain total, print "Game over" when lives reach zero. The if statement is the basic tool for this. It runs a block of code only when a condition is true, and with else and else if it chooses between several paths.

The idea is simple, but C++ adds details worth knowing well: how any value can become a condition, why = instead of == compiles, the C++17 if with initializer that keeps helper variables tightly scoped, and a first look at if constexpr, which makes decisions at compile time. This lesson covers all of them, along with the habits that keep branching code readable.

The if statement

An if statement has a condition in parentheses and a statement (almost always a block in braces) that runs only when the condition is true:

C++
if (condition) {
    // runs only when condition is true
}

Add else to run something when the condition is false. Exactly one of the two blocks runs, never both and never neither:

C++ if and else

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Change the number in the Input box and run again to take the other path. The last if has no else: when its condition is false, nothing extra happens and the program simply continues.

Always use braces, even for one-line bodies. C++ lets you write if (ok) do_it(); without them, but adding a second line later then silently puts it outside the if. Braces cost nothing and make that bug impossible. Most style guides, and this course, require them.

Conditions: what counts as true

The condition is usually a comparison or logical expression built with the operators from Comparison and Logical Operators, so it's already a bool. But C++ accepts any expression that can convert to bool:

Value in the condition Counts as true whenโ€ฆ
bool it's true
integers, char not zero
floating point not 0.0 (and NaN is true!)
pointers not nullptr
std::optional, smart pointers, streams they hold a value / are not null / are in a good state

std::string and containers do not convert to bool. Ask them directly with .empty().

C++ Values as conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Whether to write if (unread) or if (unread != 0) is a style choice. Many teams prefer the short form for pointers and optionals (it reads as "if there is one") and the explicit comparison for numbers (it reads as arithmetic). Be consistent.

else if chains

To choose between more than two paths, chain conditions with else if. C++ tests them top to bottom and runs the block of the first condition that is true. Every later condition is skipped, even if it would also be true. The final else catches everything that matched nothing.

C++ Grading with else if

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The loop reads every number from the Input box; while and do-while Loops explains while (std::cin >> score), and continue skips to the next number. Order matters here. Because 91 matches score >= 90 first, it never reaches score >= 80. If you put the >= 60 test first, every passing score would become a D. When conditions overlap, put the most specific (or the most restrictive) first.

else if isn't a separate keyword. It's just an else whose body is another if statement. Written with full braces it would nest deeper and deeper, which is why everyone formats it as a flat chain.

Nesting and guard clauses

You can put an if inside another if. That's fine one or two levels deep, but deeply nested code is hard to follow because you must remember every enclosing condition:

C++
// Hard to read: the real work is buried three levels deep
void checkout(const Cart& cart, const User& user) {
    if (!cart.items.empty()) {
        if (user.logged_in) {
            if (user.balance >= cart.total) {
                place_order(cart, user);
            } else {
                std::println("Insufficient balance");
            }
        } else {
            std::println("Please log in");
        }
    } else {
        std::println("Cart is empty");
    }
}

In a function, a cleaner shape is guard clauses: handle each problem first and return early, so the main path runs unindented at the end.

C++ Guard clauses instead of deep nesting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Each check reads as a complete sentence, and you can add a new rule without re-indenting anything. You'll write functions properly in Functions.

The dangling else

Without braces, an else belongs to the nearest unmatched if, regardless of indentation:

C++
if (temperature > 0)
    if (temperature > 30)
        std::println("hot");
else
    std::println("freezing");   // actually belongs to "if (temperature > 30)"!

With temperature = 15 this prints "freezing". The indentation lies. GCC warns (-Wdangling-else: "suggest explicit braces to avoid ambiguous 'else'"), and braces fix it for good.

if with an initializer (C++17)

Often you compute a value only to test it. Before C++17 that variable had to be declared before the if, where it stayed visible for the rest of the function. Now you can declare it inside the if, followed by a semicolon and the condition:

C++
if (init-statement; condition) { ... } else { ... }

The variable is visible in the condition and in both the if and the else blocks, and nowhere else. This is especially handy with lookups that return something you must check, such as find on a map or string:

C++ if with initializer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

You'll learn maps in std::map; here it's enough to know that find returns end() when the key is missing. An older form still works too: if (auto p = get_pointer()) declares a variable and uses its truth value as the condition. The initializer form is more general because the condition can be anything. The same syntax exists for switch and, since C++20, for range-based for.

Common mistakes

= instead of ==

if (x = 5) assigns 5 to x and then tests the result, which is 5, so it's always true. It compiles because an assignment is an expression. GCC warns with -Wall ("suggest parentheses around assignment used as truth value"). Never ignore that warning. If you really mean "assign and test", write the initializer form instead: if (int n = read(); n > 0).

Chained comparisons

if (0 < x < 10) doesn't mean "x is between 0 and 10". It evaluates 0 < x to true or false (1 or 0), then compares that with 10, which is always true. Write if (0 < x && x < 10).

A stray semicolon

if (ready); ends the if statement right there, with an empty body. The block that follows runs unconditionally.

The program below contains all three mistakes on purpose. Run it and read the warnings GCC prints with -Wall -Wextra above the output:

C++ Three bugs the compiler warns about

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Every line of output is wrong, yet the program compiles. That's why professional C++ projects compile with -Wall -Wextra and often -Werror, which turns warnings into errors (see Compilers, Flags and Optimization).

Comparing floating-point values with ==

if (0.1 + 0.2 == 0.3) is false because of rounding. Compare with a tolerance, as shown in Floating-Point Numbers.

The conditional operator for simple choices

When both branches just pick a value, the conditional operator ?: is often clearer than an if/else that assigns a variable twice:

C++
std::string_view label = (count == 1) ? "item" : "items";
int shipping = (total >= 5000) ? 0 : 499;

Use it for values, not for actions, and don't nest it deeply. It's covered in Operator Precedence and the Conditional Operator.

A preview: if constexpr and if consteval

if constexpr (condition) evaluates its condition at compile time, and the branch that isn't taken is discarded entirely. It's mainly used inside templates, where some code only makes sense for certain types:

C++
template <typename T>
void describe(T value) {
    if constexpr (std::is_integral_v<T>) {
        std::println("{} is an integer", value);
    } else {
        std::println("{} is something else", value);
    }
}

C++23 also adds if consteval, which asks "is this code being evaluated at compile time right now?". Both are explained in Compile-Time Programming. C++20's [[likely]] and [[unlikely]] attributes can be placed on a branch to hint which path is common, but measure before using them; compilers and CPUs usually predict well on their own.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. int score = 85; Which block runs? if (score >= 60) {A} else if (score >= 80) {B} else {C}

    Conditions are tested top to bottom and only the first true one runs. 85 >= 60 is true, so A runs and the rest is skipped. Put the stricter test first.
  2. 2. What does int x = 0; if (x = 7) { std::println("yes"); } do?

    = assigns. The condition's value is the assigned 7, which converts to true. GCC warns about this with -Wall.
  3. 3. In if (auto pos = s.find(':'); pos != std::string::npos) { ... } else { ... }, where can pos be used?

    A variable declared in the initializer of an if is in scope for the condition and for both branches, and ends with the whole if statement.
  4. 4. int x = 50; What does if (0 < x < 10) evaluate to?

    The expression is (0 < x) < 10. The first part becomes true (1), and 1 < 10 is true. Write 0 < x && x < 10 instead.

Summary

  • if (condition) { ... } else { ... } runs exactly one branch; else is optional.
  • Conditions convert to bool: non-zero numbers, non-null pointers and non-empty optionals are true. Strings need .empty().
  • else if chains test top to bottom and run only the first match; order overlapping conditions from most to least specific.
  • Prefer guard clauses with early return over deep nesting. Always use braces; an unbraced else binds to the nearest if.
  • C++17's if (init; condition) scopes helper variables to the if and its else.
  • Classic bugs: = for ==, 0 < x < 10, a stray ; after the condition, == on floating point. Compile with -Wall -Wextra and read the warnings.
  • if constexpr decides at compile time and is mainly for templates.

Next: switch Statements, a cleaner way to choose between many fixed values.