Conditional-Operator or Ternary-Operator in CPlusPlus

Conditional-Operator or Ternary-Operator in CPlusPlus

The Conditional-Operator evaluates an expression. If that expression is true then it will generate one output but if that expression is false then it will generate another output.

Here is an example: 3+2 = 9 ? a : b
In this example you ask a question (is 3 + 2 equal to 9 or not?) and you say if this expression is true choose the option (a) and if the expression is false choose the option (b). Since (3+2) is equal to (5) and not (9); the person has to choose the option (a).

Quite the same; the general syntax for a Conditional-Operator is as below:

Conditional-Operator Syntax

If the condition is true the expression will generate expression 1 and inverse.

Some Examples:
7 = 7 ? 4 : 6                          // generates the value 4; because 7 is equal to 7
7+1 = 6 ? 4 : 6                     // generates the value 6; because 7+1 is not equal to 6
3 > -4 ? a : b                        // generates the value a; because 3 is greater than (-4)
5 < 9 && 5 > 6 ? a : b        // generates the value b; because a logical AND is used in the expression both the conditions (5<9) and (5>6) should be true so that the expression become true.

The Conditional-Operator (?) is also called to be a ternary operator. Because it needs three operands to work on.


See Also:   Basic Operators in Programming Languages

The Conditional-Operator is also used to replace an if-else statement.

The general syntax for an if – else statement is:


For Example:

The output for the above code will be:

Programs Demonstrating Conditional-Operator:

Below you can find a program which demonstrates the idea of Conditional-Operator;


See Also:   Function OverLoading in C++

WAP to find the biggest out of 3 different numbers entered by the user in C Language:


Biggest of 3 Numbers output

Previous How to Work With Libraries in C++
Next How to Set-up an IDE for Java (+Video)

About author

Bahonar Javid
Bahonar Javid 43 posts

<p>* Computer Application Student<br /> * Co-Founder of<br /> * Love to code and Learn new languages<br /> * Enjoy playing football</p>

View all posts by this author →

You might also like