Short Hand If...Else (Ternary Operator)
Ternary Operator Introduction
C++ provides a shorthand version of if-else using the ternary operator (?:
).
It is commonly used for simple conditional assignments and inline expressions.
Only one of the two result expressions is evaluated (the chosen branch).
Syntax
variable = (condition) ? expressionIfTrue : expressionIfFalse;
Practical Example
#include <iostream>
#include <string>
int main() {
int time = 20;
std::string result = (time < 18) ? "Good day" : "Good evening";
std::cout << result;
return 0;
}
Good evening
Type Deduction & Common Pitfalls
Both result expressions must be type-compatible; otherwise implicit conversions (or a compile error) occur.
Beware with auto
: auto x = cond ? "A" : "B";
deduces const char*
. If you want a std::string
, make one side a std::string
(or declare the target type explicitly).
#include <string>
int main() {
auto a = true ? "A" : "B"; // a is const char*
auto b = true ? std::string("A") : "B"; // b is std::string
(void)a; (void)b;
}
Selecting by Reference
If both result expressions are lvalues of the same type, the ternary yields an lvalue—useful for picking a reference.
int main() {
int x = 5, y = 9;
int& ref = (x < y) ? y : x; // ref refers to y
ref = 42; // modifies y
}
Nested Ternary
Ternary operators can be nested to evaluate multiple conditions, but readability suffers quickly:
#include <iostream>
#include <string>
int main() {
int x = 10, y = 20, z = 30;
std::string result = (x >= y && x >= z) ? "x is largest" :
(y >= z) ? "y is largest" :
"z is largest";
std::cout << result;
return 0;
}
z is largest
Best Practices
- Use the ternary operator for short, simple conditions.
- Avoid it for complex or multi-branch logic (use if-else or switch).
- Do not nest beyond one level; prioritize readability.
- Ensure both result expressions have compatible types to avoid surprises.
- Be careful with side effects—only the selected branch runs, but keep expressions simple.