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 :

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.

Tags: , ,

Leave A Response