C Language: Conditional Operator (? :) Tutorial | Ternary Operator/ Conditional operator tutorial with Examples

Spread the love

Conditional Operator ( ? and : ) 

Conditional operator is a ternary operator. Ternary operator means it requires three operands.
i.e Left side expression, Middle Expression, Right side Expression.
This is written as.

            Value = Expression 1 ? Expression 2 : Expression 3 ;

How Conditional Operator Works :

Firstly Expression 1 is evaluated, if Expression 1 is true or non zero then the return value is Middle Expression that is Expression 2. If the Expression 1 is false or Zero then return value is Expression 2 i.e Right side Expression.
Example :
Max = X < Y ? Y : X ;
Here first the expression X < Y is evaluated, if the value of expression is true then the Max is X.otherwise the value of Y becomes the value of Conditional Expression.
Suppose X = 10 and Y = 20 then above condition is 
Max = 10 < 20 ? 20 : 10 ;
First expression 10< 20 is evaluated, since it is true value 20 becomes the value of Max.
let’s take one more example 
a = 5 > 8 : 20 : 30 ;
first 5 > 8 is evaluated since it is false value of a (variable a) is 30.

Quick Notes about Conditional Operator :

  • Number of Question marks(?) and Colons(:) should be Equal.
             Ex 1:     a = 10 ? 20 : 30 ; 
                          number of question marks and colons are equal. and value of a is 20 because 10(test                                     Expression) is non-zero.
             Ex 2:     a = 2 > 5 ?10 : 20 : 30 ;
                          Error : number of Question marks and Colons are not equal.
  • Every Colon should be Followed by Question mark.
             Ex :       a = 10 < 15 ? 1 : 20 : 5 ? 30 ;
                          Error : Second colon is not followed by Question mark.     

Program : Understanding Conditional operator with Example Program :

Program to calculate Minimum Value among three Numbers :
  1. #include <stdio.h>
  2. int main(void) {
  3.         int x,y,z,min;
  4.         x = 10;
  5.         y = 20;
  6.         z = 5 ;
  7.         min = (x<&& x<z) ? (x) : (y<z) ? (y) : (z) ;
  8.         printf(“Minimum Value is : %d n,min);
  9.         return 0;
  10. }
Output :

Minimum Value is : 5

Related Tutorials :


Venkatesh Macha

Hi Guys, I am Venkatesh Macha. I am a programmer, Presently working as a Software Engineer. I love Linux and Open Source. Apart from that, I love to explore new technologies and things.

You may also like...

1 Response

Leave a Reply