Ternary Operator
The ternary operator gets its name because it takes three operands, unlike most operators (which take one or two). It has this form:
condition ? value1 : value2C++ evaluates condition. If it’s true, the whole expression evaluates to value1. If it’s false, it becomes value2. Only one of the two values ever gets computed, the other is skipped entirely, just like the branches of an if/else.
Before you run the following code, look at the highlighted lines and predict the values produced by the ternary expressions:
That last one is worth pausing on. age >= 18 is already a bool. Wrapping it in a ternary that just returns true or false is redundant. It would have been better to write bool canVote = age >= 18; instead.
The ternary operator earns its keep as long as the expression doesn’t just echo a condition that’s already a boolean.
It’s an expression, not a statement
This is the core distinction between if/else and the ternary operaton.
An if/else is a statement. It controls which block of code runs, but it doesn’t produce a value you can use directly. So, you can’t write something like int x = if (y > 0) { 1 } else { -1 };. That’s not valid C++.
The ternary operator, on the other hand, is an expression that produces a value all ready for use.
Chaining ternaries
You can nest ternary operators to express more than two outcomes:
The trick to reading this is seeing that value2 of one ternary can itself be another ternary. Read it as a chain of “otherwise, check the next thing”: if the score isn’t 90 or above, fall to the condition in the next ternary, and so on down to the final 'F'.
That said, don’t push this too far. Once you’re nesting more than two or three levels, an if/else if/else chain will read much better.
Checkpoint
Given this chain, what does label hold when speedMph is 45?
int speedMph = 45;
std::string label = (speedMph > 65) ? "over limit"
: (speedMph > 55) ? "warning"
: (speedMph > 40) ? "caution"
: "normal";What does result equal after this runs?
int a = 4, b = 4;
int result = (a > b) ? a++ : b++;
std::cout << result << " " << a << " " << b;