C++ if, else if and else

The if statement runs code only when a condition is true.

#include <iostream>

int main() {
    int marks = 72;
    if (marks >= 40) {
        std::cout << "You passed\n";
    }
}
Output

You passed

if, else if and else

#include <iostream>

int main() {
    int marks = 76;
    if (marks >= 90) {
        std::cout << "A+\n";
    } else if (marks >= 75) {
        std::cout << "A\n";
    } else if (marks >= 60) {
        std::cout << "B\n";
    } else {
        std::cout << "C or below\n";
    }
}
Output

A

Conditions with &&, || and !

#include <iostream>

int main() {
    int age = 25;
    bool has_license = true;
    if (age >= 18 && has_license) {
        std::cout << "You can drive\n";
    } else if (age >= 18) {
        std::cout << "Get a license first\n";
    }
}
Output

You can drive

What is true?

In C++ the number 0 is false and every other number is true. Pointers: nullptr is false.

#include <iostream>

int main() {
    std::cout << std::boolalpha << static_cast<bool>(0) << ' ' << static_cast<bool>(-5) << ' ' << static_cast<bool>(0.0) << '\n';
}
Output

false true false

if with an initializer (C++17)

You can declare a variable inside the if line. It lives only inside the if and else blocks.

#include <iostream>
#include <map>
#include <string>

int main() {
    std::map<std::string, int> stock{{"pen", 40}, {"book", 0}};

    if (auto it = stock.find("pen"); it != stock.end()) {
        std::cout << it->first << " has " << it->second << '\n';
    } else {
        std::cout << "not found\n";
    }
}
Output

pen has 40

Common mistakes

  • = instead of == (the compiler warns with -Wall).
  • A semicolon right after the condition: if (x > 5);
  • Missing braces when you add a second line. Always use braces.

if constexpr (C++17)

The condition is checked when the program is compiled. The other branch is not even compiled. It is used in templates.

#include <iostream>
#include <string>
#include <type_traits>

template <typename T>
std::string describe(T value) {
    if constexpr (std::is_integral_v<T>) {
        return "integer " + std::to_string(value);
    } else {
        return "something else";
    }
}

int main() {
    std::cout << describe(5) << ", " << describe(2.5) << '\n';
}
Output

integer 5, something else

Note: Keep the main (normal) path of the code without extra nesting. Return early when a check fails. Next: C++ switch.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.