Loading lessons...
Short Hand If... else (Ternary)
Short Hand If...Else (Ternary)
The ternary operator squeezes a small if/else choice into one line. It is perfect for picking one of two values.
The shape
variable = (condition) ? valueIfTrue : valueIfFalse;
- First evaluate the
condition. - If it is true, the whole expression becomes
valueIfTrue. - If it is false, the whole expression becomes
valueIfFalse.
An example
#include <iostream>
using namespace std;
int main() {
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result << endl;
return 0;
}
Since 20 < 18 is false, result holds the value after the colon: "Good evening."
Same as a regular if/else
The line above:
string result = (time < 18) ? "Good day." : "Good evening.";
is the one-line version of:
string result;
if (time < 18) {
result = "Good day.";
} else {
result = "Good evening.";
}
Use it for short choices
The ternary shines when the choice is a single quick value. For longer logic, stick with a plain if/else so the code stays easy to read.
TL;DR
- Shape:
variable = (condition) ? valueIfTrue : valueIfFalse; - True picks the value before the colon; false picks the one after.
- It is a one-line version of a full if/else.
- Keep it to small, simple selections.