Use of Conditional (Ternary) Operator in C++

By: Baski Emailed: 1700 times Printed: 2204 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

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.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


1. View Comment

There is another similar discussion on use of ternery operator.
IMHO: condition should be simple enough and should be bi-valued and not use this operator in a multi-valued by daisy chaining the expression.
The good coder writes elegent code other write codes. And every one writes code that works!!!

View Tutorial          By: Syed Mamun Raihan at 2008-09-10 11:29:42

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Baski
Compiling multiple source files and specifying classpath using javac
The equals() Method example in Java
Default Values for Data Types in Java
JSP Example to connect to MS SQL database using Tomcat Connection Pool
<convertNumber> and <convertDateTime> in JSF
Enable/Disable Scripting Elements in JSP
Using calloc() Function in C
lseek() sample program in C
Arrays of Structures example program in C
The Basic Syntax Expression Language in JSP
Initialization of Pointer Arrays in C
Functions returning non-integer values in C
Increment and Decrement Operators in C
Getting Started with C
What is JSF (JavaServer Faces)?

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Using cout in C++
Demonstration of Prefix and Postfix operators in C++
Use of Conditional (Ternary) Operator in C++
Demonstrating global and local variables in C++
Passing parameters to a function by value in C++
The Birth, history and need for C++
Tutorial on Classes and Members in C++
Constructors and Destructors in C++
const Member Functions in C++
Where to Put Class Declarations and Method Definitions in C++
Tutorial on Inline Implementation in C++
Classes with Other Classes as Member Data in C++
Looping with the keyword goto in C++
continue and break statements in C++
while (1) Loops in C++
Most Emailed Articles (in C++)
while (1) Loops in C++
How to handle Exceptions in C++
Character String Literals in C++
Calculating total based on the given quantity and price in C++
A Brief History of C++
Difference between Procedural, Structured, and Object-Oriented Programming
C++ and Object-Oriented Programming
Getting Started with C++
Using cout in C++
Using Comments in a C++ Program
Using functions in C++
How to use Enumerated constants in C++
Demonstration of Prefix and Postfix operators in C++
The if Statement in C++
Advanced if Statements in C++