Thursday, July 11, 2013

Conditional Operator in C

Conditional Operator is a special kind of Operator which is used to check whether the condition mentioned is true or not and then perform an action based on the result. It is represented by
cond?exp1:exp2
which means, to evaluate the condition first. If the condition is true, then execute exp1, if it is false, execute exp2.

Here are some examples of how do we use it.

  • z=(x>y)?x:y 
It means that if x is greater than y, then take x, else if y is greater than x, take y.

This conditional Operator just works like an if else statement.
  • if(x>y)
  • z=x;
  • else
  • z=y;
The above code is similar to the example we have mentioned earlier. 

This conditional Operator is also called as Ternary Operator as it uses three operands.