Ternary Operators in C

What are ternary Operators ?

Ternary operators are used by programmers to simply multi-line if else statement and condensed into single line.

result = binaryCondition ? valueReturnedIfTrue : valueReturnedIfFalse;
question

How to use a Ternary Operator?

result = binaryCondition ? valueReturnedIfTrue : valueReturnedIfFalse;

Example - 

max = a > b ? a : b;
  • The condition part- which defines the condition which we are choosing upon
  • The first statement  – decides what will happen, if the condition is true.
  • The second statement part – decides what will happen, if the condition is false.

Example 1

#include<stdio.h>

int main() 
{
    int a = 10, b = 20;
    
    int max = a > b ? a : b ;
    
    printf("The larger number is %d", max); 
    
    return 0;
}

Output

The larger number is 20

More

Ternary operator can be taken as a substitute for other decision-making statements, like if, if-else, etc. as it helps in raising a condition and deciding the output, based on the condition, it is also favourable, because:

  • uses less space than the if-else statement.
  • decreases the complexity of the program
  • Easy to understand

Example 2

The above can also be simplified as –

#include<stdio.h>

int main() 
{
    int a = 10, b = 20;
    
    a > b ? printf("%d is greater",a) : printf("%d is greater",b);
    
    return 0;
}

Output

20 is greater

One comment on “Ternary Operators in C”