Conditional operator in C | Ternary Operator in C

Preview

Conditional operator in C

This operator is known as ternary operator because it has three operands. Ternary operator is represented as ?: . It is used to check a condition and depending upon the condition, particular instruction is executed by the compiler.

Syntax:

Condition? Block1: Block2;

Condition is any relational or logical expression. Which will be checked to see which block of statements should be executed.

Block1 refers to C language statement which will be executed if condition is true.

Block2 refers to C language statement which will be executed if condition is false.


Program to demonstrate the use of conditional operator
#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