If Else in C++

Branching with if and else in C++ is straightforward.

#include <iostream>

int main() {
    // Here's a basic example.
    if (7 % 2 == 0) {
        std::cout << "7 is even" << std::endl;
    } else {
        std::cout << "7 is odd" << std::endl;
    }

    // You can have an `if` statement without an else.
    if (8 % 4 == 0) {
        std::cout << "8 is divisible by 4" << std::endl;
    }

    // Logical operators like `&&` and `||` are often
    // useful in conditions.
    if (8 % 2 == 0 || 7 % 2 == 0) {
        std::cout << "either 8 or 7 are even" << std::endl;
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in the current
    // and all subsequent branches.
    if (int num = 9; num < 0) {
        std::cout << num << " is negative" << std::endl;
    } else if (num < 10) {
        std::cout << num << " has 1 digit" << std::endl;
    } else {
        std::cout << num << " has multiple digits" << std::endl;
    }

    return 0;
}

To compile and run this C++ program:

$ g++ if-else.cpp -o if-else
$ ./if-else
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in C++, you need parentheses around conditions, and braces are optional for single-statement blocks (though it’s often considered good practice to include them for clarity).

C++ does have a ternary operator (?:) for simple conditional expressions, which can be used as an alternative to simple if-else statements.