Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Conditions and conditional control flow

Conditional control flow chooses which part of a program executes based on a condition. Learn if, else if, else, conversion to bool, short-circuit evaluation of logical operators, and value selection with ?:.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

if (condition) {
    statements;
} else if (other_condition) {
    other_statements;
} else {
    fallback_statements;
}

condition ? value_if_true : value_if_false

Conditional control flow (conditional control flow) lets a program choose an action based on a condition. When execution reaches an ordinary if, its condition is contextually converted to bool: true selects the first branch, while false selects the else branch, if present. A numeric zero and a null pointer convert to false; nonzero numbers and non-null pointers convert to true.

else if is another if nested inside else. Conditions in this chain are checked in order until the first true condition; its branch executes and later branches are skipped. A final else handles the remaining cases. Use braces {} to make branch boundaries clear: without them, else binds to the nearest if that does not already have an else. Use == for comparison, not the assignment operator =.

The built-in logical operators && and || short-circuit from left to right: && skips its right operand when the left is false, and || skips it when the left is true. Thus, count > 0 && total / count >= 4 does not perform division if count > 0 is false. Do not substitute the bitwise operators & and |, which do not provide this skipping behavior.

if selects a statement, whereas condition ? value_if_true : value_if_false is an expression selecting a result; only one of its two result operands is evaluated. An ordinary if does not exempt an unexecuted branch from code validity requirements. if constexpr is a separate construct with a constant condition and branch-discarding rules useful in templates.

The example uses constructs available in C++23. The supplied site hosts an evolving working draft, not a frozen C++23 publication. A compiler flag does not attest production runtime use or successful test execution.

Examples

#include <iostream>

int main() {
    const int total = 12;
    const int count = 3;

    if (count == 0) {
        std::cout << "empty\n";
    } else if (count > 0 && total / count >= 4) {
        std::cout << "enough\n";
    } else {
        std::cout << "not enough\n";
    }

    std::cout << (total > 0 ? "positive" : "non-positive") << '\n';
}

Result

enough
positive

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources