← Back to C++ Course | Chapter 3: Operators | Lesson 8 of 9

C++ Ternary Operator

Introduction to Ternary Operator

The ternary operator condition ? valueIfTrue : valueIfFalse packs a simple if-else choice into a single expression, evaluating to one of two values depending on whether the condition is true. It's the only operator in C++ that takes three operands, which is why it's also called the conditional operator.

Example: Introduction to Ternary Operator

cpp
#include <iostream>

int main() {
	int age = 20;
	std::string result = (age >= 18) ? "Adult" : "Minor";
	std::cout << result << std::endl;
	return 0;
}

Assigning Values Directly

Because the ternary operator is itself an expression rather than a statement, you can use it directly on the right side of an assignment, like int max = (a > b) ? a : b;, avoiding the need for a separate multi-line if-else block just to pick a value. This keeps simple two-way decisions compact and readable.

Example: Assigning Values Directly

cpp
#include <iostream>

int main() {
	int a = 10, b = 20;
	int max = (a > b) ? a : b;
	std::cout << max << std::endl;
	return 0;
}

Nested Ternary Operators

Nesting one ternary operator inside another lets you handle more than two outcomes, such as grade = (score >= 90) ? A : (score >= 80) ? B : C;, but readability drops fast past two levels of nesting. For anything beyond a simple three-way choice, an if-else ladder is usually clearer.

Example: Nested Ternary Operators

cpp
#include <iostream>

int main() {
	int score = 85;
	char grade = (score >= 90) ? 'A' : (score >= 80) ? 'B' : 'C';
	std::cout << grade << std::endl;
	return 0;
}

Printing directly with Ternary Operator

Embedding a ternary expression directly inside cout, like cout << (isEven ? "Even" : "Odd");, lets you print one of two messages without writing a separate if-else block just to choose the text. This works because cout << expects an expression, and a ternary operator evaluates to exactly that.

Example: Printing directly with Ternary Operator

cpp
#include <iostream>

int main() {
	int num = 7;
	bool isEven = (num % 2 == 0);
	std::cout << (isEven ? "Even" : "Odd") << std::endl;
	return 0;
}

Ternary Operator with Math Calculations

You can put arithmetic directly inside either branch of a ternary, such as total = (isMember) ? price * 0.9 : price;, computing a discounted or full price in one line depending on the condition. This keeps small conditional calculations self-contained without needing a full if-else block around them.

Example: Ternary Operator with Math Calculations

cpp
#include <iostream>

int main() {
	double price = 50.0;
	bool isMember = true;
	double total = (isMember) ? price * 0.9 : price;
	std::cout << total << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.