Conditional Statements Ternary Operators - Abdul Rehman
Conditional Statements Ternary Operators - Abdul Rehman
In C++, the ternary operator (also known as the conditional operator) can be used to replace if...else (/cpp-
programming/if-else) in certain scenarios.
Its syntax is
The ternary operator takes 3 operands ( condition , expression1 and expression2 ). Hence, the name ternary
operator.
Example : C++ Ternary Operator
#include <iostream>
#include <string>
using namespace std;
int main() {
double marks;
cout << "You " << result << " the exam.";
return 0;
}
Output 1
Suppose the user enters 80. Then, the condition marks >= 40 evaluates to true . Hence, the first expression
"passed" is assigned to result .
Output 2
Now, suppose the user enters 39.5. Then, the condition marks >= 40 evaluates to false . Hence, the second
expression "failed" is assigned to result .
#include <iostream>
using namespace std;
int main() {
// Create a variable
int number = -4;
if (number > 0)
cout << "Positive Number";
else
cout << "Negative Number!";
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
int number = -4;
string result;
return 0;
}
Output
Negative Number!
Here, both programs give the same output. However, the use of the ternary operator makes our code more
readable and clean.
Note: We should only use the ternary operator if the resulting statement is short.
Nested Ternary Operators
It is also possible to use one ternary operator inside another ternary operator. It is called the nested ternary
operator in C++.
Here's a program to find whether a number is positive, negative, or zero using the nested ternary operator.
#include <iostream>
#include <string>
using namespace std;
int main() {
int number = 0;
string result;
return 0;
}
Output
Number is Zero
Here,
(number == 0) is the first test condition that checks if number is 0 or not. If it is, then it assigns the string
value "Zero" to result .
Else, the second test condition (number > 0) is evaluated if the first condition is false .
Note: It is not recommended to use nested ternary operators. This is because it makes our code more
complex.