Conditional operator in C | Ternary Operator in C
Conditional operator/ternary operator has three operands. It is represented as ?: . It tests a condition and depending upon condition, specific instruction gets executed .
Syntax:
Condition? Statement: Statement2;
Condition represents a condition made using relational or logical operators.
Statement1 represents the statement to be executed if condition is true.
Statement2 represents the statement to be executed if condition is false.
Program to demonstrate the use of conditional operator in C |
#include<stdio.h> int main() { int a=11,b=5,c; c=a>b?a:b; printf("\nLargest value=%d",c); return (0); } |
Output |
Largest value=11
|
In the above program, expression c=a>b?a:b is evaluated.
Variable a contains 11 and b contains 5
Condition a>b is true, so statement after question mark (?) will be evaluated and c will contain value of a i.e. 11.