Test your Programming knowledge

50% users failed to get the best score. It's your turn to test now.
Questions curated by the expert mentors at codzify.com

Start Quiz

Article

Ternary Operator in C Language - Codzify Tutorials

1 min 55 sec read

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") ; 

Recommended Articles

Did you found this article helpful?

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor