Ternary Operator in C Language - Codzify Tutorials

1 min 55 sec read Basic


What are Conditional Operators ?

The conditional operators ? and : are sometimes called ternary operators since they take three arguments. In fact, they form a kind of foreshortened if-then-else. It is very easy to understand Ternary Operator in C . Consider the following syntax below for better understanding,

Syntax :-

 expression 1 ? expression 2 : expression 3 

What this expression says is: "if expression 1 is true (that is, if its value is non-zero), then the value returned will be expression 2, otherwise the value returned will be expression 3"

It's equivalent if statement will look like this

 if(expression 1)
    {
    expression 2;
    }
    else
    {
    expression 3;
    }

Example :-

/* Copyright @codzify 2017 */
#import <stdio.h>
#import <conio.h>

void main( ) {
int a , b;

   a = 10;
   printf( "Value of b is %d\n", (a == 1) ? 20: 30 );

   printf( "Value of b is %d\n", (a == 10) ? 20: 30 );

Output :-

Value of b is 30
Value of b is 20

Short Description of Example :-

(a == 1) ? 20: 30

Firtsly a == 1 is being evaluated but since a=10 condition becomes false so output will be 30.

(a == 10) ? 20: 30

Firtsly a == 10 is being evaluated but since a=10 condition becomes true so output will be 20 :)

It's equivalent if statement will look like this

  a = 10;
  if(a == 1 ) 
      printf("20");       --Just for understanding 
  else
      printf("30") ; 

How was the tutorial? Nice. Right?



Deep Concept videos to crack the highly-piad interviews.

Chekout out our Youtube Channel to get detailed video content on important topics in interviews.



What is your Interview Score?

Test your skillset with the curated questions created by experts around the globe.

Book a free test slot. Now !.

It usually takes 30 mins for an online test and this test will be MCQ based. Get detailed analytics based on your test and recommedations with personalised roadmaps.

Book a test slot. Now!

Have questions about the trial coding class?

Chat with our experts to discuss

Connect on WhatsApp


Recommended tutorials

#online compiler for c     #python for programming    

#dfs and bfs algorithm     #programming with c language

#storageclass in C    #listcomprehension in python