Saturday, August 1, 2015

The Conditional/Ternary Operators.

Sometimes conditional operators" ? and : "  are called as ternary operators as they take three arguments.In the form of if then else.The syntax is

expression 1 ? expression 2 : expression 3
the following expression can be read as if expression 1 is true then it will return expression 2 else it will return expression 3.
Let's understand with the help of example:

//example of if-else 
int a,x;
scanf("%d",&a);
if(a%2= =0)
x=1;
else
x=0;

from above example it is clear that if condition is true it will give the value of x =1 otherwise it will give x=0.
Now if we want to write the above case in terms of conditional operator then it will be written as


//example using conditional operator

int a,x;
scanf("%d",&a);
x=(a%2==0 ? 1 : 0);

Here 1 would be assigned to x if a%2= =0 is true otherwise 0 will be assigned to x.

Few points that we should know about conditional operator is that :
1) It's not necessary that these operators can be used only in arithmetic statements.
2) It can be used as nested format.

Note :
if expression will be given in format like
x<y?z=1:z=0;

this statement will give the error this can be overcome by placing the expression 3 in the parentheses i.e.(z=0)

 x<y?z=1:(z=0);

If we do not put the parentheses the compiler believes that 0 is being assigned to the result to the left of second=,and thus gives the error.

Limitation of conditional operator:The limitation of this operator is that after the " ? " or after the " " only one C statement can occur .