Skip to content

Conditional operator#

The conditional (ternary) operator selects between two values based on a condition.

Syntax#

The operator has the form condition ? true_value : false_value.

true ? "yes" : "no"
// result: "yes" (string)
// input: x = -1
x > 0 ? "positive" : "not positive"
// result: "not positive" (string)
10 % 2 == 0 ? "even" : "odd"
// result: "even" (string)

Type requirements#

The condition must evaluate to a boolean. Both value branches must have the same type.

true ? 1 : 2
// result: 1 (int)
"true" ? 1 : 2
// error: no matching overload for '_?_:_' applied to '(string, int, int)'
true ? 1 : "2"
// error: no matching overload for '_?_:_' applied to '(bool, int, string)'

Short-circuit evaluation#

Only the selected branch is evaluated.

// input: x = 0
x != 0 ? 100/x : 0
// result: 0 (int)

Nesting#

Ternary expressions can be nested. Use parentheses or newlines for clarity.

true ? (false ? "a" : "b") : "c"
// result: "b" (string)
// input: x = 33, target = 42
x > target ? "too big" :
x < target ? "too small" : "just right!"
// result: "too small" (string)

See also#