Table of Contents
Ternary operator in C
A ternary operator in C is the second form of if-else, which can be used rather than using if-else statements. First, it will check whether a given condition is true or not and then the expressions will be evaluated accordingly. If the condition is true, then expression 1 gets evaluated. Otherwise, expression 2 gets evaluated.
Syntax: condition? expression 1: expression 2;
Example
#include<stdio.h> int main() { int age; printf("Enter age\n"); scanf("%d",&age); (age>18)? printf("eligible to vote") : printf("not eligible to vote"); return 0; }
Output
Explanation
If the condition ( age>18 ) is true, then expression 1 will get executed. Otherwise, expression 2 will get evaluated. Since 22 is more than 18, expression 1 gets executed, and “eligible to vote” gets printed.
0 Comments