DevAcademia lesson/C++ Basics
Short Hand If...Else
Topic progressTopic 41 of 109 - 38% complete
~6 min lesson23 learning blocks5 code examples1 checks/interactions
Lesson outline
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
Practical Example
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).
Selecting by Reference
If both result expressions are lvalues of the same type, the ternary yields an lvalue - useful for picking a reference.
Nested Ternary
Ternary operators can be nested to evaluate multiple conditions, but readability suffers quickly:
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.
Was this topic clear?