Conditional Operator in C – C provides an called as the conditional operator (?:) which is closely related to the if/else structure.
The conditional operator is C’s only ternary operator – it takes three operands. The operands together with the conditional operator form a conditional expression.
The first operand is a condition, the second operand represents the value of the entire conditional expression it is the condition is true and the third operand is the value for the entire conditional expression if the condition is false.
The syntax of Conditional Operator in C
(condition)? (expression1): (expression2);
If condition is true, expression1 is evaluated else expression2 is evaluated. Expression1/Expression2 can also be further conditional expression i.e. the case of nested if statement
Let us see the following examples:
(i) x= (y<20) ? 9: 10;
This means, if (y<20), then x=9 else x=10;
(ii) printf (“%s\n”, grade>=50? “Passed”: “failed”);
The above statement will print “passed” grade>=50 else it will print “failed”
(iii) (a>b) ? printf (“a is greater than b \n”): printf (“b is greater than a \n”);
If a is greater than b, then first printf statement is executed else second printf statement is executed.