Ternary Operator in C++
What is ternary operator in C++?
Here in this page we will discuss about Ternary Operator in C++ also known as conditional operator. The conditional operator is similar to the if-else statement in that it follows the same algorithm, but the conditional operator takes less space and helps to write the if-else statements in the shortest possible way.Ternary Operator in C++
The syntax of ternary operator is as follows:
(Test condition)? Statement1:Statement2
If the condition is true statement 1 is evaluated and if it is false, statement 2 is evaluated.
Understanding Syntax of Ternary operator
The conditional operator is a decision-making operator whose statement is evaluated based on the test condition
Here, Test condition is evaluated and
- if the condition is true, statement1 is executed.
- And, if the condition is false, statement2 is executed.
The ternary operator takes 3 operands (Test condition , statement1 and statement2 ).
Hence, the name ternary operator.
Understaning the syntax
The syntax of conditional operator can be visualized as a if else statement as:-
variable=(Test condition)?Statement1:Statement2;
here the condition will be checked and if the condition is true then the Statement1 will be assigned to the variable and if the condition is false Statement2 will be assigned to the variable.
if (Test condition) { variable = Statement1 ; } else { variable = Statement2 ; }
Lets take a practical example to understand this. I the below code the value of age will be checked if the age is greater than or equal to 18 then the value of vote is eligible otherwise its not eligible.
#include <iostream> using namespace std; int main() { int age = 4; string vote; // Using ternary operator vote = (age >= 18) ? "Eligible" : "Not Eligible"; cout << vote << endl; return 0; }
Output:
Not Eligible
Nested Ternary Operator
#include <iostream> using namespace std; int main() { int a = 10, b = 20, c = 30, res; res = a > b ? (a > c ? a : c) : (b > c ? b : c); // nesting of ternary operator cout << "maximum number is : " << res; return 0; }
Output:
maximum number is : 30
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment