position: fixed; top: auto !important; margin-left: 112px;

Ternary Operators in C

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


Previous Next Article







codzify.com


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Linkedin
Twitter
Facebook

Copyright 2018. All rights reserved.