Skip to content
C++ Better Explained
Go back
C++ Ternary Operator: How to Use ? : in C++
Edit page

C++ Ternary Operator: How to Use ? : in C++

The ternary operator is a compact way to write a simple if/else in a single expression. Once you know it, you’ll see it everywhere — in assignments, function calls, and print statements.


The Syntax

condition ? value_if_true : value_if_false

Example:

int a = 10, b = 20;
int max = (a > b) ? a : b;  // max = 20

This is equivalent to:

int max;
if (a > b) {
    max = a;
} else {
    max = b;
}

The ternary version is one line instead of six. For simple value selection, it’s much more concise.


Basic Examples

Find the larger of two numbers:

int a = 7, b = 3;
int larger = (a > b) ? a : b;  // 7

Absolute value:

int n = -5;
int abs_n = (n >= 0) ? n : -n;  // 5

Print “even” or “odd”:

int x = 4;
cout << (x % 2 == 0 ? "even" : "odd") << endl;  // even

Clamp a value:

int score = 105;
int clamped = (score > 100) ? 100 : score;  // 100

Using the Ternary in Different Contexts

In a function call:

cout << "You " << (score >= 60 ? "passed" : "failed") << endl;

In a return statement:

bool isAdult(int age) {
    return (age >= 18) ? true : false;
    // Simpler: return age >= 18;
}

In an initializer:

string status = (temperature > 100) ? "boiling" : "not boiling";

Ternary vs if/else: When to Use Each

The ternary operator is best when:

if/else is better when:

Good use of ternary:

int fee = (isMember) ? 0 : 10;           // Clean value selection
string label = (count == 1) ? "item" : "items";  // Singular/plural

Bad use of ternary (use if/else instead):

// Trying to do too much in one line
result = (condition) ? (doThing1(), doThing2(), value1) : (doThing3(), value2);

Nested Ternary (Avoid This)

Technically valid, practically unreadable:

// Don't do this
int grade = (score >= 90) ? 5 :
            (score >= 80) ? 4 :
            (score >= 70) ? 3 :
            (score >= 60) ? 2 : 1;

Write it as an if/else chain instead:

int grade;
if (score >= 90)      grade = 5;
else if (score >= 80) grade = 4;
else if (score >= 70) grade = 3;
else if (score >= 60) grade = 2;
else                  grade = 1;

The if/else version is immediately readable. Nested ternaries force the reader to trace brackets and evaluate operator precedence — it’s not worth the brevity.


Common Mistake: Using Ternary for Side Effects

// Don't do this — ternary is for expressions, not statements
(x > 0) ? cout << "positive" : cout << "negative";

Write it as if/else:

if (x > 0) cout << "positive";
else       cout << "negative";

Operator Precedence

The ternary operator has lower precedence than most operators but higher than assignment. To be safe, parenthesize the condition:

int result = a > b ? a : b;    // Works, but easy to misread
int result = (a > b) ? a : b;  // Clearer — recommended

Also be careful when combining with assignment:

// This assigns 0 if x > 0, else assigns x = 5 (probably not what you want)
int y = x > 0 ? 0 : x = 5;  // Don't do this

// Write clearly:
int y = (x > 0) ? 0 : 5;
If you're looking to go deeper with C++, the C++ Better Explained Ebook is perfect for you — whether you're a complete beginner or looking to solidify your understanding. Just $19.

Summary

AspectTernary ? :if/else
Returns a valueYesNo (statements only)
Multiple statementsNoYes
ReadabilityGood for simple casesBetter for complex logic
NestingPossible but avoidNatural and clear
AssignmentNatural fitRequires extra variable

The ternary operator is a useful shorthand for selecting between two values. Keep it simple — one condition, one true value, one false value. When in doubt, use if/else.



Take Your C++ Further

If you’re looking to go deeper with C++, the C++ Better Explained Ebook is perfect for you — whether you’re a complete beginner or looking to solidify your understanding. Just $19.

👉 Get the C++ Better Explained Ebook — $19

📋

Free Download: The 10 Mistakes Every C++ Beginner Makes

A free 1-page checklist that shows the exact traps that slow down every C++ beginner — so you can avoid them from day one.

🔒 No spam. Unsubscribe anytime.


Edit page
Share this post on:

Previous Post
C++ string vs char Array: Which Should You Use?
Next Post
C++ User Input: How to Use cin to Read Input