Ternary Operator in C

by | Aug 15, 2021 | C

Home » C » Ternary Operator in C

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

Ternary operator in C

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.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author