Saturday 1 August 2015

Ternary Operator in C



In C programming we often use ternary operator (? :). The ternary operator is a conditional operator similar to the way conditional expression if-else.


if(Condition)
{
       Statement;
}
else
{
       Statement;
}

Ternary operator(?:) is used as

Variable = condition? Value if true: value if false

For example if we wish to implement c code for toilet indicator (RED: In use, GREEN: Ready) we may write.


if(Status == In_use)
{
     Indicator = RED;
}
else
{
     Indicator = GREEN;
}

The above code can be replaced by ternary operator

Indicator  =  (Status == In_use)  ? RED : GREEN;


 The two forms are nearly equivalent, though ternary ?: is an expression and  if-else is a statement

No comments:

Post a Comment