Wednesday 7 April 2021

Conditional Operator in C

Conditional operator is a Ternary operator available in list of operators in the C language. It requires three operands. Conditional statements are used to make decision based upon condition. Ternary operator requires two special symbols (‘?’ and ‘:’) to express it.

The program execution of conditional operator is just like if-else conditional statement.

Syntax of conditional operator

Expression 1? Expression 2: Expression 3;

Working of Ternary Operator

As in Expression 1? Expression 2:  Expression3. Expression 1 is the Boolean expression. If Expression1 evaluates to 0 which is a Boolean expression then that simply means FALSE and if the Expression1 evaluates to 1 this simply means TRUE therefore Expression3 or Expression2 will get evaluated based on Expression1.

For example

#include<stdio.h>

int main ()

{

    int a, c;

    printf("Enter the number  ");

    scanf("%d", &a);

    c = (a>5) ? printf("True") : printf("False");

}

Output:



15 comments: