The ternary operator
- C++ course
- Beginner
- Lesson 39/116
- 5 min
Learn to write a conditional expression in one line with ? :.
The ternary operator
The ternary operator is a way to write a simple if/else on a single line. Its form is condition ? true_value : false_value and it produces a value.
For example: std::string result = (age >= 18) ? "Drive" : "Wait";. This does the same as a four-line if/else but is shorter in an assignment context. For complex conditions readability drops; then if/else is preferred.
Ternary in assignment
The ternary shines in assignment statements. Writing int max = (a > b) ? a : b; finds the larger of two numbers in one line. The same with if/else would take three or four lines.
Because the ternary produces a value, you can also use it directly as in std::cout << ((a > b) ? a : b). Nesting ternary expressions is possible but hurts readability, so it is usually avoided.
Practice Find the larger number
The a and b variables are given. Use the ternary operator in the form int max = (a > b) ? a : b; to assign the larger one to max and print it with std::cout. The output must be 12.
Starter code
#include <iostream>
int main() {
int a = 7;
int b = 12;
// Assign the larger one to max with ternary and print
return 0;
}Sample solution
#include <iostream>
int main() {
int a = 7;
int b = 12;
int max = (a > b) ? a : b;
std::cout << max << std::endl;
return 0;
}Expected output
12
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the ternary operator
std::string result = (age >= 18) ____ "Drive" : "Wait";
std::string result = (age >= 18) ? "Drive" : "Wait";
Explanation: The ? operator picks the left value when the condition is true.
2 Match each ternary part to its role
| Term | Meaning |
|---|---|
? |
When condition is true |
: |
When condition is false |
(age >= 18) |
The condition |
"Drive" |
The true value |
3 What is the result of (5 > 3) ? "yes" : "no"?
auto r = (5 > 3) ? "yes" : "no";- "no"
- true
- 5
- "yes" Correct answer
Explanation: 5 > 3 is true, so the result is "yes".