Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Conditional operator ?:

The ?: operator selects one of two expressions based on a condition. It evaluates only the selected branch, but the result type depends on both branches. In suitable cases, the result can designate an existing object rather than produce a new value.

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

Syntax

condition ? expression_if_true : expression_if_false

The conditional operator ?: takes three operands: condition ? expression_if_true : expression_if_false. The condition is contextually converted to bool and evaluated before the selected branch. For true, the second operand is evaluated; for false, the third is evaluated—never both.

This is an expression, not an if statement: its result can be used in initialization or a larger expression. The result type and value category depend on both branches, not just the selected one. An ordinary unselected branch must still be valid; skipping its evaluation does not remove type errors. For example, true ? 1 : 2.5 has type double.

If both branches are lvalues of the same type, the result is also an lvalue. In the example, selected binds to left, so modification through that reference changes left. The expression involving denominator does not divide by zero because it selects the 0 branch.

The operator groups right-to-left: a ? b : c ? d : e means a ? b : (c ? d : e). Use parentheses or if for readability with complex choices. The supplied standard URL points to an evolving working draft, not a frozen C++23 publication.

Examples

#include <iostream>

int main() {
    int left = 4;
    int right = 9;
    bool choose_left = true;

    int& selected = choose_left ? left : right;
    selected += 1;

    int denominator = 0;
    int quotient = denominator != 0 ? 12 / denominator : 0;

    std::cout << left << ' ' << right << '\n';
    std::cout << quotient << '\n';
}

Result

5 9
0

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