Use of Conditional (Ternary) Operator in C++

By: Baski  

The conditional operator (?:) is C++'s only ternary operator; that is, it is the only operator to take three terms.

The conditional operator takes three expressions and returns a value:

(expression1) ? (expression2) : (expression3)

This line is read as "If expression1 is true, return the value of expression2; otherwise, return the value of expression3." Typically, this value would be assigned to a variable.

Program below shows an if statement rewritten using the conditional operator.

A demonstration of the conditional operator.

1:   // demonstrates the conditional operator
2:   //
3:   #include <iostream.h>
4:   int main()
5:   {
6:      int x, y, z;
7:      cout << "Enter two numbers.\n";
8:      cout << "First: ";
9:      cin >> x;
10:     cout << "\nSecond: ";
11:     cin >> y;
12:     cout << "\n";
14:     if (x > y)
15:       z = x;
16:     else
17:       z = y;
19:     cout << "z: " << z;
20:     cout << "\n";
22:     z =  (x > y) ? x : y;
24:     cout << "z: " << z;
25:     cout << "\n";
26:        return 0;
27: }
Output: Enter two numbers.
First: 5

Second: 8

z: 8
z: 8

Analysis: Three integer variables are created: x, y, and z. The first two are given values by the user. The if statement on line 14 tests to see which is larger and assigns the larger value to z. This value is printed on line 19.

The conditional operator on line 22 makes the same test and assigns z the larger value. It is read like this: "If x is greater than y, return the value of x; otherwise, return the value of y." The value returned is assigned to z. That value is printed on line 24. As you can see, the conditional statement is a shorter equivalent to the if...else statement.

Archived Comments

Most Viewed Articles (in C++ )

Latest Articles (in C++)

Comment on this tutorial