In this C++ tutorial, you will learn how the ternary operator, also called the conditional operator, selects one of two expressions based on a condition. You will also see its syntax, equivalent if...else logic, nested ternary expressions, return statements, type conversion, and cases where if...else is clearer.
C++ Ternary Operator
The C++ ternary operator uses the symbols ? and : to choose between two expressions. It is called a ternary operator because it works with three operands: a condition, an expression for the true case, and an expression for the false case.
It is useful when a program needs to select a value with a short condition. Unlike an if...else statement, the conditional operator itself is an expression, so its result can be assigned to a variable, returned from a function, or used inside another expression.
Syntax of C++ Ternary Operator
Following is the syntax of Ternary Operator.
condition ? expression1 : expression2;
The condition is evaluated first. If it is true, only expression1 is evaluated and its value becomes the result. If it is false, only expression2 is evaluated and its value becomes the result.
How the C++ Conditional Operator Maps to if…else
A ternary expression is often a compact way to express a simple two-way value choice. For example, the following assignment:
string result = (score >= 40) ? "Pass" : "Fail";
can be written with if...else as follows:
string result;
if (score >= 40) {
result = "Pass";
} else {
result = "Fail";
}
Both forms select one of two values. The ternary form is usually easier to read when the condition and both result expressions are short. For multi-step logic, if...else is generally clearer.
C++ Ternary Operator Examples
1. Check Whether a Number Is Even or Odd Using the Ternary Operator
Following is a simple example program demonstrating the usage of Ternary Operator in C++.
We are checking if the number is even and assigning a string to str.
C++ Program
#include <iostream>
using namespace std;
int main() {
int a = 11;
string str = (a%2 == 0) ? "Even Number": "Odd Number";
cout << str << endl;
}
Output
Odd Number
Here, a % 2 == 0 is false because 11 leaves a remainder of 1 when divided by 2. Therefore, the false expression, "Odd Number", is selected.
2. Nested Ternary Operator to Find the Maximum of Three Numbers
Ternary Operator can be nested. Meaning, we can write a ternary operator for one of the values in the outer ternary operator.
Let us go through an example program, where we shall find the maximum of three numbers using nested ternary operator.
C++ Program
#include <iostream>
using namespace std;
int main() {
int a = 11;
int b = 5;
int c = 23;
int max = (a>b) ? ((a>c) ? a : c) : ((b>c) ? b : c) ;
cout << max << endl;
}
Output
23
The outer condition first compares a and b. Depending on that result, an inner ternary expression compares the remaining candidates. Parentheses make the grouping explicit and easier to follow.
3. Return a Value from a C++ Function with the Ternary Operator
Because the conditional operator produces a value, it can be used directly in a return statement.
#include <iostream>
using namespace std;
int larger(int a, int b) {
return (a > b) ? a : b;
}
int main() {
cout << larger(18, 12) << endl;
}
Output
18
If a > b is true, the function returns a; otherwise, it returns b.
C++ Ternary Operator Without an Else Branch
In standard C++, the conditional operator cannot omit the false expression. The complete form requires both expressions:
condition ? expression_if_true : expression_if_false
If you only need to perform an action when a condition is true and do nothing otherwise, an if statement is clearer and directly expresses that intent.
if (temperature > 30) {
cout << "Hot day" << endl;
}
C++ Ternary Operator with Different Result Types
The second and third operands do not always have to be written with exactly the same type. C++ applies its conditional-expression type rules and, when a valid conversion exists, can produce a common result type.
bool useWholeNumber = false;
double value = useWholeNumber ? 10 : 2.5;
cout << value << endl;
Output
2.5
In this example, one branch is an int and the other is a double. The selected numeric value is compatible with the double result. If the two operands cannot form a valid conditional expression under C++ conversion rules, the code will not compile.
Only One Ternary Result Expression Is Evaluated
After the condition is evaluated, C++ evaluates only the selected result expression. This matters when an operand calls a function or has another side effect.
int x = 5;
int result = (x != 0) ? (100 / x) : 0;
When x is zero, the expression 100 / x is not evaluated; the false expression 0 is selected instead.
Multiple Statements and the C++ Ternary Operator
The operands of ?: are expressions, not general statement blocks. Although C++ has expression features that can combine operations, using the ternary operator for several actions usually makes the code harder to read. Use if...else when each branch needs multiple statements.
if (loggedIn) {
loadProfile();
showDashboard();
} else {
showLoginPage();
logAccessAttempt();
}
When to Use the C++ Ternary Operator Instead of if…else
- Use the ternary operator when one short condition selects between two simple values or expressions.
- Use it for compact assignments and return expressions where the intent remains easy to read.
- Prefer
if...elsewhen either branch contains several operations, nested decisions, or long expressions. - Use parentheses around nested ternary expressions so the grouping is obvious to readers.
A useful rule is to optimize for readability rather than for the fewest lines of code. A short conditional expression can be clearer than an if...else block, while a deeply nested ternary expression can be harder to maintain.
C++ Ternary Operator Summary
The C++ ternary operator has the form condition ? expression1 : expression2. It evaluates the condition and then evaluates only one of the two result expressions. Since the operator produces a value, it works well in assignments and return statements. Standard C++ requires both the true and false expressions, and if...else is usually the better choice when the logic involves multiple statements or becomes difficult to read.
In this C++ Tutorial, we learned the syntax and usage of Ternary Operator in C++.
TutorialKart.com