Ternary Operator in C++

Prev Tutorial Next Tutorial

Ternary Operator in C++

If any operator is used on three operands or variable is known as Ternary Operator. It can be represented with ? : . It is also called as conditional operator

Ternary Operator

Advantage of Ternary Operator

Using Ternary Operator reduce the number of line codes and improve the performance of application.


expression-1 ? expression-2 : expression-3

In the above symbol expression-1 is condition and expression-2 and expression-3 will be either value or variable or statement or any mathematical expression. If condition will be true expression-2 will be execute otherwise expression-3 will be executed.


a<b ? cout<<"a is less" : cout<<"a is greater";

Flow Diagram

Ternary Operator

Find largest number among 3 numbers using ternary operator

Example Ternary Operator in C++


void main()
int a, b, c, large;
cout<<"Enter any three number: ";
large=a>b ? (a>c?a:c) : (b>c?b:c);
cout<<"Largest Number is: "<<large;


Enter any three number: 5 7 2
Largest number is 7
Prev Tutorial Next Tutorial