if Statement (C++)

An if statement runs a block of code only when its condition is true. You can add else if to test more conditions and else to handle everything else.

C++

The condition goes in parentheses and must evaluate to a boolean (or something convertible to one). Curly braces group the statements that belong to each branch.

Chaining else if lets a program choose between several mutually exclusive options.

Syntax

if (condition) { ... } else if (other) { ... } else { ... }

Examples

C++

#include <iostream>

int main() {
    int score = 75;
    if (score >= 90) {
        std::cout << "A" << std::endl;
    } else if (score >= 70) {
        std::cout << "B" << std::endl;
    } else {
        std::cout << "C" << std::endl;
    }
    return 0;
}

Output:

B

Learn it in a lesson

See also

Back to the Dictionary