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.

question

Syntax:

result = binaryCondition ? valueReturnedIfTrue : valueReturnedIfFalse;

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.

Code for Ternary operator in C

Example 1

Run
#include <stdio.h>
#include <stdlib.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 –
Run
#include <stdio.h>
#include <stdlib.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

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

One comment on “Ternary Operators in C”