Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C++ If ... Else

The if statement runs code only when a condition is true. With else and else if, a program chooses between several paths.

if, else if, else

#include <iostream>

int main() {
    int marks;
    std::cout << "Marks (0-100): ";
    std::cin >> marks;

    if (marks >= 90) {
        std::cout << "Grade A\n";
    } else if (marks >= 75) {
        std::cout << "Grade B\n";
    } else if (marks >= 50) {
        std::cout << "Grade C\n";
    } else {
        std::cout << "Grade D\n";
    }
    return 0;
}
You type
78
Output
Marks (0-100): Grade B

Conditions are checked from the top, and the first true one wins. Order them from the most specific to the most general. Always write the braces, even for one statement: adding a second line later then cannot slip outside the if.

Combining conditions

#include <iostream>

int main() {
    int age = 15;
    bool hasTicket = true;
    if (age >= 12 && hasTicket) {
        std::cout << "You may enter.\n";
    }
    if (age < 13 || age > 64) {
        std::cout << "Reduced price.\n";
    } else {
        std::cout << "Full price.\n";
    }
    return 0;
}
Output
You may enter.
Full price.

The conditional operator

condition ? a : b chooses between two values in one expression:

#include <iostream>
#include <string>

int main() {
    int n = 7;
    std::string kind = (n % 2 == 0) ? "even" : "odd";
    std::cout << n << " is " << kind << "\n";
    return 0;
}
Output
7 is odd

if with an initializer (C++17)

C++17 lets an if declare a variable that exists only inside the if and its else, keeping it close to where it is used:

#include <iostream>
#include <string>

int main() {
    std::string text = "hello world";
    if (auto pos = text.find(' '); pos != std::string::npos) {
        std::cout << "first word: " << text.substr(0, pos) << "\n";
    } else {
        std::cout << "one word only\n";
    }
    return 0;
}
Output
first word: hello

Common mistakes

  • **= instead of ==**: if (x = 5) stores 5 and is always true. With -Wall the compiler warns.
  • A semicolon after the condition: if (x > 5); ends the if right there, and the block below always runs.
  • **Wrong order of else if tests**: the first true test wins, so put the most specific test first.
  • Testing a range like in maths: if (10 < x < 20) is always true in C++. Write if (x > 10 && x < 20).
  • Deep nesting: several if statements inside each other are hard to read. Returning early from a function (if (!valid) return;) often keeps the code flat.

Good practice

Keep conditions short and give complicated ones a name: bool canEnter = hasTicket && age >= 12; followed by if (canEnter) reads better than a long expression in the if. Handle the unusual case first and the normal case after it, so the main path of the code is easy to follow.

Practice exercises

  1. Read a year and print whether it is a leap year (divisible by 4, not by 100 unless by 400).
  2. Read three numbers and print the largest.
  3. Read a temperature and print "cold", "pleasant" or "hot".