What the conditional operator does
The conditional operator chooses between two values in a single expression. It is written as condition ? value_if_true : value_if_false. If the condition is true, the result is the first value. If it is false, the result is the second.
Because it produces a value, it can be used where an if-else block cannot, such as on the right side of an assignment or as an argument to a function call. It takes three operands, unlike unary operators in c, which take one. That is why it is also called the ternary operator.
Basic syntax
#include <iostream>
int main() {
int a = 7;
int b = 3;
int larger = (a > b) ? a : b;
std::cout << larger << '\n'; // prints 7
}
The three parts are:
- The condition,
(a > b). It can be any expression that converts tobool. For numbers, zero is false and any other value is true. The condition is usually a check made with c comparison operators such as>and==. The parentheses are optional, but they make the code easier to read. - The first value,
a, used when the condition is true. - The second value,
b, used when the condition is false.
The ? separates the condition from the first value, and the : separates the first value from the second. Both are required.
Only the chosen branch runs
Only one of the two values is evaluated. The other is skipped, which matters when an expression changes a variable:
int x = 0;
int y = 0;
int result = (x == 0) ? ++x : ++y;
// result is 1, x is 1, and y is still 0
Setting a value
The conditional operator works well for setting a const variable, because its value must be set when it is declared:
int score = 72;
const int bonus = (score >= 50) ? 5 : 0; // bonus is 5
Using it inside cout
A conditional expression placed inside << needs its own parentheses:
int count = 1;
std::cout << (count == 1 ? "item" : "items") << '\n'; // prints item
Without the parentheses, << is grouped before ?: and ==, so the expression is read as ((std::cout << count) == 1) ? .... That is not what you meant, and the code will not compile.
Nesting and grouping
Conditional operators can be nested. They group from right to left, so this:
int n = -4;
int sign = (n > 0) ? 1 : (n < 0) ? -1 : 0; // sign is -1
is read as a first test and then a second test in the false branch. The parentheses are not required, but they make the structure clear. Nested chains get hard to read quickly. Two levels are usually fine. For more choices, a switch case statement in c or an if-else chain is usually clearer.
Precedence and assignment
The conditional operator has lower precedence than arithmetic, comparison and logical operators. An expression such as this one is grouped as you would expect:
int a = 2;
int b = 5;
int c = 4;
int x = a + b > c ? a : c; // x is 2
Assignment has even lower precedence, so x = cond ? 1 : 2; needs no extra parentheses. Still, parentheses around a longer condition help any reader see the grouping at a glance.
Both values need compatible types
The two values must convert to a common type. If both are numbers of different types, the usual arithmetic conversions apply:
auto v = true ? 1 : 2.5; // v is a double with the value 1.0
Mixing unrelated types, such as a string literal and an int variable, does not compile.
Where it cannot be used
Both values are expressions, not statements. You cannot put return, break, continue or a variable declaration in either branch. A throw expression is the one exception, because it is allowed as an operand.
You also cannot overload the conditional operator, so its behavior for your own types is fixed.
Conditional operator or if-else?
Use the conditional operator to pick a single value. Use an if-else statement when a branch needs several statements, or when the branches do different things, such as printing messages or changing several variables. For those cases, the if else statement syntax in c is the better fit.
Common mistakes
- Using
=where==is meant. In(x = 0) ? a : b, the assignment setsxto 0, the result 0 is false, and the code always picksb. - Leaving out the parentheses inside output. This is the
<<problem shown above. - Nesting too deeply. Long chains of
?:are hard to check. Split them up or use a clearer form. - Mixing types that have no common conversion. Both values must be able to meet in one type.
Summary
The conditional operator, condition ? value_if_true : value_if_false, is a short expression that picks one of two values. Only the chosen value is evaluated, nested uses group from right to left, and both values must share a type. Use it for short choices that produce a value, and reach for an if-else statement when a branch does more than produce a value.