There is  a special operator called  conditional operator in  C++ programming language, denoted by ?: symbol. It is way different from the other operators in C++ programming language and provides a convenient way to take an action depending on the truth or falsity of a condition.

Lets see how this operator works.

First thing we need to know is that condition operator is a ternary operator. This means it takes three operands. Its general form is: expression ? result 1 : result 2

Here ‘expression’ can evaluate to true or false. If it evaluates to true, ‘result 1’ is the result of the conditional statement else ‘result 2’ is the result.

NOTE : The result of the conditional expression can be assigned to a variable.

Consider the following program as an example :

using namespace std;

int main()
 int a=10,b=70;
 cout <<"Maximum number is :" << (a>b ? a : b) ;
 int max = a>b ? a : b ;
 cout<<"\nGreatest number is : "<<max;
 return 0;

In this program, we wish to find out greater of two given integers using the conditional operator.

We may or may not store the result in a separate variable. The program shows both the ways.

As you can see the condition a>b is evaluated, if it is true, max becomes equal to ‘a’ and if the condition is false, max gets value  ‘b’ . In this case, 10 is not greater than 70, so the condition evaluates to false and thus max gets value of b which is 70.

use of Conditional Operator in C++

Hope you are clear with this topic. Let us know your doubts and queries in comments below.


Founder & Senior Editor of and Editor at Sakshi is currently pursuing MCA. She is a foodie and has a unique love for learning computer programming languages. Follow her on Google + | Facebook | Twitter. Contact her at [email protected] for feedback and sending tips.

Tags: , ,

Leave A Response