In this C++ tutorial, you will learn the syntax of Ternary Operator, and how to use this operator with the help of examples covering different scenarios.
C++ Ternary Operator
Ternary operator is used to select one of the two values based on the result of a boolean expression.
Syntax of Ternary Operator
Following is the syntax of Ternary Operator.
condition ? expression1 : expression2;
The condition
is evaluated. If it is true, the ternary operator evaluates expression1
and returns the value. If it is false, the ternary operator evaluates expression2
and returns the value.
Examples
1. A simple example for 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
2. Nested Ternary Operator
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
Conclusion
In this C++ Tutorial, we learned the syntax and usage of Ternary Operator in C++.