Skip to content
Laviyx Learn

Try

C++ course menu

C++ if, else if and else: Making Decisions

Learn C++ conditions with if, else if and else: writing conditions, combining them with && and ||, nested if statements, if with an initializer (C++17), the dangling-else trap, and common mistakes like = instead of ==.

Beginner11 min readUpdated
On this page

Programs need to make decisions: give a discount if the order is large, show an error if the password is wrong. The if statement runs a block of code only when a condition is true.

if#

C++
#include <iostream>

int main() {
    int temperature = 34;

    if (temperature > 30) {
        std::cout << "It's a hot day.\n";
    }
    std::cout << "Have a nice day!\n";
}
Output
It's a hot day.
Have a nice day!

The condition goes in parentheses, and the code to run goes in a block { }. If the condition is false, the block is skipped and the program continues after it.

if ... else#

else gives the code to run when the condition is false:

C++
#include <iostream>

int main() {
    int marks = 35;

    if (marks >= 40) {
        std::cout << "Pass\n";
    } else {
        std::cout << "Fail\n";
    }
}
Output
Fail

Exactly one of the two blocks runs.

else if: several choices#

Chain conditions with else if. C++ checks them from top to bottom and runs only the first block whose condition is true:

C++
#include <iostream>

int main() {
    int marks = 82;

    if (marks >= 90) {
        std::cout << "Grade A\n";
    } else if (marks >= 75) {
        std::cout << "Grade B\n";
    } else if (marks >= 60) {
        std::cout << "Grade C\n";
    } else {
        std::cout << "Grade F\n";
    }
}
Output
Grade B

82 is not ≥ 90, but it is ≥ 75, so Grade B prints and the remaining checks are skipped. Because the checks run in order, the else if (marks >= 75) branch already knows marks is below 90.

Combining conditions#

Use && (and), || (or) and ! (not) from Operators:

C++
#include <iostream>

int main() {
    int age = 16;
    bool with_parent = true;

    if (age >= 18 || with_parent) {
        std::cout << "Entry allowed\n";
    }
    if (age >= 13 && age <= 19) {
        std::cout << "Teenager\n";
    }
    if (!(age >= 18)) {
        std::cout << "Minor\n";
    }
}
Output
Entry allowed
Teenager
Minor

Nested if statements#

An if can sit inside another if. This is useful when a second question only makes sense after the first:

C++
#include <iostream>

int main() {
    bool logged_in = true;
    bool is_admin = false;

    if (logged_in) {
        if (is_admin) {
            std::cout << "Admin dashboard\n";
        } else {
            std::cout << "User dashboard\n";
        }
    } else {
        std::cout << "Please log in\n";
    }
}
Output
User dashboard

Deep nesting gets hard to read. Often you can flatten it with &&, or handle the simple case first and return early.

Braces are optional, but use them#

If a branch has a single statement, the braces can be left out:

C++
if (marks >= 40)
    std::cout << "Pass\n";

This is risky: if you later add a second indented line, it will not be part of the if, even though it looks like it. Always using braces avoids that bug.

The dangling else#

Without braces, an else belongs to the nearest if, whatever the indentation says:

C++
#include <iostream>

int main() {
    int x = 5;
    if (x > 10)
        if (x > 20)
            std::cout << "big\n";
    else
        std::cout << "small\n";   // belongs to if (x > 20), not if (x > 10)!
    std::cout << "done\n";
}
Output
done

Since x > 10 is false, nothing inside runs, not even the else. GCC and Clang warn about this ("suggest explicit braces to avoid ambiguous else") when you compile with -Wall. With braces the structure is explicit and there is no surprise.

if with an initializer (C++17)#

You can declare a variable inside the if itself. It exists only in the if and else blocks, which keeps it from leaking into the rest of the function:

C++
#include <iostream>

int main() {
    int price = 1200;
    int quantity = 3;

    if (int total = price * quantity; total > 3000) {
        std::cout << "Free delivery on " << total << '\n';
    } else {
        std::cout << "Delivery charge applies on " << total << '\n';
    }
}
Output
Free delivery on 3600

Values as conditions#

Any number can be used as a condition: 0 is false, and everything else is true. if (count) means if (count != 0). It is legal, but writing the comparison is usually clearer.

Common mistakes#

Practice#

Practice exercise

A shop gives 20% off orders of 5000 or more, 10% off orders of 2000 or more, and no discount otherwise. For an order of 3500, print the discount percentage and the final amount.

Show solution
C++
#include <iostream>

int main() {
    double order = 3500;
    int discount = 0;

    if (order >= 5000) {
        discount = 20;
    } else if (order >= 2000) {
        discount = 10;
    }

    double final_amount = order - order * discount / 100;
    std::cout << "Discount: " << discount << "%\n";
    std::cout << "Pay: " << final_amount << '\n';
}
Output
Discount: 10%
Pay: 3150

Practice exercise

Write a program that checks whether year = 2024 is a leap year: divisible by 4, except years divisible by 100, unless they are also divisible by 400. Then try 1900 and 2000 by changing the value.

Show solution
C++
#include <iostream>

int main() {
    int year = 2024;

    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        std::cout << year << " is a leap year\n";
    } else {
        std::cout << year << " is not a leap year\n";
    }
}
Output
2024 is a leap year

1900 is not a leap year (divisible by 100 but not 400); 2000 is.

Key takeaway#

Finished this lesson?