What is Ternary Operator in C programming with example

What is Ternary Operator in C programming with example

Ternary Operator

In the C language ternary operator is allowing for executing or running any code based on the given value to the condition, and the condition result value of the expression returned to the output. The important use of a ternary operator decreases the number of lines of codes and increases the performance of the application.

Most of the research articles claimed that the expression result is faster than a statement result (conventional if-else condition). Ternary operator contains 3 expressions; Expression1, Expression2, and Expression3. Expression1 holds the condition to check, Expression2 will hold true value evaluated by Expression1 condition, and Expression3 will hold false value evaluated by Expression1 condition.

Advantages:

  • It reduces the code.
  • Improves performance.
  • Overcome conventional use of if and else condition always.

How does ternary operator work in C language?

C language ternary operator works based on the ternary operator(?), If the condition is evaluated true then it executes the true expression value at the left-hand side of the colon(:) symbol and if the condition is evaluated false then it executes false expression value at the right-hand side of the colon(:) symbol.

Syntax

Expression1?Expression2:Expression3;

Example

#include<stdio.h>
int main(){
 int age;

   printf("Enter age");
   scanf("%d", &age);
  
   age >= 18 ? printf("Adult") : printf("Not Adult");
   return 0;
}

 

TYPES OF INSTRUCTIONS IN C PROGRAMMING

How to Start Blogging in 2024 and Start Earning