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"; 13: 14: if (x > y) 15: z = x; 16: else 17: z = y; 18: 19: cout << "z: " << z; 20: cout << "\n"; 21: 22: z = (x > y) ? x : y; 23: 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
1. There is another similar discussion on use of ternery operator.
IMHO: condition should be sim
View Tutorial By: Syed Mamun Raihan at 2008-09-10 11:29:42
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++