Online Classes

Results can only be achieved if you have the focused direction and crystal clear knowledge. To achieve this, you need a mentor. We will help you out by connecting with an expert mentor in the field.

Learn More

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

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