Cpp - Operator Conditional Expressions

Introduction

The following code uses if statement to check if input is valid.

Demo

#include <iostream> 
using namespace std; 

int main() //  w  ww  .j  a  v a  2s. c  om
{ 
    float x, y; 

    cout << "Type two different numbers:\n"; 
    if( !(cin >> x && cin >> y) ) // If the input was 
    {                             // invalid. 
        cout << "\nInvalid input!" << endl; 
    } 
    else 
    { 
        cout << "\nThe greater value is: " 
              << (x > y ? x : y)  << endl; 
    } 

    return 0; 
}

Result

Conditional Operator

The conditional operator ?: forms an expression that produces either of two values, depending on a condition.

A conditional expression is often a concise alternative to an if-else statement.

       
expression ? expression1 : expression2 
  • expression is evaluated first.
  • If the result is true, expression1 is evaluated;
  • if not expression2 is executed.
  • The value of the conditional expression is therefore either the value of expression1 or expression2.
z = (a >= 0) ? a : -a; 

The code above assigns the absolute value of a to the variable z.

If a has a positive value of 12, the number 12 is assigned to z.

If a has a negative value, for example -8, the number 8 is assigned to z.

Since this sample program stores the value of the conditional expression in the variable z, the statement is equivalent to

if( a > 0 ) 
     z = a; 
else 
     z = -a; 

Precedence

The conditional operator precedence is higher than that of the comma and assignment operators but lower than all other operators.