Ternary Operator in C: Usage and Examples

Rumman Ansari   Software Engineer   2024-07-04 05:09:57   11086  Share
Subject Syllabus DetailsSubject Details 4 Questions 11 Program
☰ TContent
☰Fullscreen

Table of Content:

Ternary Operator (?:)

A conditional operator is a ternary operator, that is, it works on 3 operands.

Conditional Operator Syntax

conditionalExpression ? expression1 : expression2

The conditional operator works as follows:

  • The first expression conditionalExpression is evaluated first. This expression evaluates to 1 if it's true and evaluates to 0 if it's false.
  • If conditionalExpression is true, expression1 is evaluated.
  • If conditionalExpression is false, expression2 is evaluated.

C conditional Operator

#include
int main(){
   char February;
   int days;
   printf("If this year is leap year, enter 1. If not enter any integer: ");
   scanf("%c",&February);

   // If test condition (February == 'l') is true, days equal to 29.
   // If test condition (February =='l') is false, days equal to 28. 
   days = (February == '1') ? 29 : 28;

   printf("Number of days in February = %d",days);
   return 0;
}
 

Output

If this year is leap year, enter 1. If not enter any integer: 1
Number of days in February = 29