Learn C++ - C++ Conditional Operators






The conditional operator, written ?:.

The general form looks like this:

expression1 ? expression2 : expression3

If expression1 is true, then the value of the whole conditional expression is the value of expression2.

Otherwise, the value of the whole expression is the value of expression3.

Example

The following code uses the conditional operator to determine the larger of two values.


#include <iostream> 
using namespace std; 
/*from  ww  w . ja  va 2  s  . c o  m*/
int main() 
{ 
     int a, b; 
     cout << "Enter two integers: "; 
     cin >> a >> b; 
     cout << "The larger of " << a << " and " << b; 
     int c = a > b ? a : b;   // c = a if a > b, else c = b 
     cout << " is " << c << endl; 
     return 0; 
} 

The code above generates the following result.