100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C++

Ternary Operator in C++

Learn how the C++ ternary conditional operator (?:) provides a compact alternative to if-else for simple value selection.

OperatorsBeginner5 min readJul 7, 2026
Analogies

1. Intro

The ternary operator, written condition ? expr1 : expr2, is C++'s only operator that takes three operands. It is a compact expression form of an if-else statement: if condition is true, the whole expression evaluates to expr1; otherwise it evaluates to expr2. Because it's an expression (not a statement), it can be used directly inside assignments, function calls, or cout statements.

🏏

Cricket analogy: The ternary wicketsLeft > 3 ? "declare" : "bat on" is like a captain making a split-second call mid-over - one quick expression replacing a whole paragraph of if-else reasoning about the innings.

2. Syntax

cpp
result = (condition) ? valueIfTrue : valueIfFalse;

3. Explanation

The ternary operator evaluates condition first. If it's true, only expr1 is evaluated (and becomes the result); expr2 is skipped entirely. If condition is false, only expr2 is evaluated. This means the ternary operator also short-circuits — exactly one of the two branch expressions runs, never both. It's best used for simple, single-value selection; nesting many ternary operators for complex logic hurts readability and an if-else chain is usually clearer.

🏏

Cricket analogy: Like an umpire who checks only the front-foot no-ball line first - if it's a no-ball, the 'wicket' branch never even gets evaluated - the ternary checks condition and executes only one branch, never both.

Only one branch of the ternary operator is ever evaluated, similar to short-circuiting. int x = (n != 0) ? (100 / n) : 0; is safe because 100 / n is never evaluated when n == 0, avoiding a division-by-zero.

4. Example

cpp
#include <iostream>
using namespace std;

int main() {
    int age = 20;
    string status = (age >= 18) ? "Adult" : "Minor";
    cout << "Status: " << status << endl;

    int n = 0;
    int result = (n != 0) ? (100 / n) : 0;
    cout << "Result: " << result << endl;
    return 0;
}

5. Output

text
Status: Adult
Result: 0

6. Key Takeaways

  • The ternary operator condition ? expr1 : expr2 is a compact, expression-based alternative to if-else.
  • It is the only ternary (three-operand) operator in C++.
  • Only the selected branch expression is evaluated — the other is skipped, similar to short-circuit behavior.
  • Avoid deeply nested ternary chains; prefer if-else for complex multi-branch logic.

Practice what you learned

Was this page helpful?

Topics covered

#CStudyNotes#Programming#TernaryOperatorInC#Ternary#Operator#Syntax#Explanation#StudyNotes#SkillVeris#ExamPrep