Conditional Operator is also known as Turnary Operator. It is an alternate method to using a simple if-else. It checks the condition and executes the statement depending on the condition.
Syntex
condition?expression1:expression2;if condition is True or value 1 means expression1 will execute.
if condition is False or value 0 means expression2 will execute.
Example:
Consider the statement
a=7,b=5
c=(a>b) ? a:b;
after execution the value of c=7
Example 1:
#include<stdio.h>
int main()
{
int a=7,b=5,c;
c=(0) ? a:b; // c=5
printf("c=%d\n",c);
c=(1) ? a:b; // c=7
printf("c=%d\n",c);
return 0;
}
Example 2:
#include<stdio.h>
int main()
{
int a=7,b=5,c;
c=(a>b) ? a:b;
printf("c=%d",c);
return 0;
}
Example :3
// Conditional operator using multiple function
#include<stdio.h>
int comp();
int prin1();
int prin2();
int main()
{
comp()?prin1():prin2();//multiple function using Turnary Operator
return 0;
}
/* Comparing the values in comp()[function]
int comp()
{
int a=7,b=5;
if(a<b)
{return 0;}
if(a>b)
{return 1;}
}
int prin1() // printing function 1
{
printf("A is bigger\n");
return 0;
}
int prin2() // printing function 2
{
printf("B is bigger\n");
return 0;
}