Loading lessons...
The Conditional (Ternary) Operator
C++ Conditional Operator (Ternary)
The ternary operator is the compact way to pick one of two values. It is a little if/else squeezed into one line.
The shape
condition ? valueIfTrue : valueIfFalse
- First, decide on the
condition. - If it is true, the result is
valueIfTrue. - If it is false, the result is
valueIfFalse.
Example
int time = 20;
string msg = (time < 18) ? "Good day." : "Good evening.";
cout << msg << endl; // Good evening.
Since 20 < 18 is false, the part after the : wins.
Choosing between two values
int a = 7;
int b = 3;
int bigger = (a > b) ? a : b; // 7
The ternary works great for one simple choice.
When not to use it
For longer or nested logic, a normal if/else is much easier to read. The ternary shines on short, single-value decisions only.
TL;DR
result = condition ? valueA : valueB.- If the condition is true take
valueA, otherwise takevalueB. - Reading gets difficult for big bodies; use it for small decisions.