Conditional operator in C | Ternary Operator in C

Preview

Conditional operator in C

This operator also known as ternary operator has three operands. It is represented as ?: . It checks a condition and depending upon the condition, particular instruction is executed .

Syntax:

Expression? Code1: Code2;

Expression represents some relational or logical expression. Whose output decides which block of statements will  execute.

Code1 represents instruction which will execute if expression is true.

Code2 represents instruction which will execute if expression is false..


Program
#include<stdio.h>
int main()
{
int a=11,b=5,c;
c=a>b?a:b;
printf(“\nc=%d”,c);
return (0);
}
Output
c=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. 15.



 

Lesson tags: conditional operator of c, operator to apply conditions in c, ternary operator of c
Back to: C Programming Language