Conditional Operator/Ternary Operator in C++

C++ offers Conditional Operator (?:) that stores a value depending upon a condition. Conditional operator returns one value if condition is true and returns another value if condition is false. The general form of Conditional Operator ?: is as follows :

Syntax of Conditional Operator :

expression1 ? expression2 : expression3  (or)
condition_expression ? True_expression : False_Expression ;

Explanation :

If expression1 evaluates to true, i.e. 1, then the value of the whole expression is the value of expression2, otherwise, the value of the whole expression is the value of expression 3.

Conditional operator is also called Ternary Operator, Because it requires three operands/expressions.

Example of Conditional Operator:

 result = marks >=33 ? ‘P’ : ‘F’;

The identifier result will have ‘P’ if the test expression marks>=33 evaluates to true(1) otherwise result will have value ‘F’ .

Nested Conditional Operator – 

The Conditional Operator can also be nested. i.e. any of the expression2 or expression3 can itself be another conditional operator. For example,

result = marks >=33 ? (marks>=75) ? ( ‘S’ : ‘P’) : ‘F’;

  • The identifier result will have ‘S’ if the test expression marks>=33 as well as the test expression marks>=75   evaluates to true(1),
  • The identifier result will have ‘P’ if the test expression marks>=33 evaluates to True(1) but the text expression marks>=75 evaluates to False(0),
  • The identifier result will have ‘F’ if the test expression marks>=33 as well as the test expression marks>=75   evaluates to False(0),

Some Important Notes about Conditional Operator –

1) We can assign a value to a Conditional Expression. The result of the 
conditional operator (?:) is an lvalue, provided that the true and false 
part values, both are of same type.
An Example :

int a,d ; 
float value;
cin>>value;
value>500 ? a:d = 10 ; 

This code segment initializes value of a or d depending upon the condition
value>500 . 
So, If value is greater than 500, then x is initialized to 10,
otherwise y is initialized to 10.

2) The below code is incorrect -

int a ;
const int d=100;         //d is not an lvalue 
float value;
cin>>value;
value>500 ? a:d = 10 ;   // Incorrect

constant values and constant identifiers are not lvalues and can appear 
only to the right side of an assignment operator.

Example of C++ program for Conditional Operators –

#include<iostream.h>
int main()
   {
   int num;
   cout<<"Enter the number : ";
   cin>>num;
   cout<<endl;
   (num%2==0)?cout<<num<<" is an Even number.":cout<<num<<" is an 
                                                   Odd number.";
   return 0;
   }

Output :

Enter the number : 51
51 is an odd number.
     

Incoming search terms:

  • conditional operator in c program

Leave a Reply