Reputation: 3891
How this code works .Here i
variable gets assignment of 55
value .But why the if
statement fails since i gets 55
not 0
, here else statement executed.How this interpretation happens .
As i expected output
is Test Skills 55
but its not.
#include<stdio.h>
void main()
{
int i;
i=0;
if(i=55,0,10,0)
printf("Test Skills %d",i);
else
printf("C Programing %d",i);
}
Can any one explain how it behaves in above code?
Upvotes: 1
Views: 590
Reputation: 12797
,
operator executes from left to right. So the last value is 0
that makes the if
false.
if(i=55,0,10,0) => if(i,0,10,0) => if(55,0,10,0) => if(0) => which returns false
^^^^-> Value of i
i
is still 55 because ,
has the lowest precedence .
,
operator executes it's left expression and returns the result of right expression as a result of ,
operator.
Other thing to note here is assignment operator has higher precedence then ,
. That's why i
got the value 55
.
Upvotes: 0
Reputation: 106042
The comma expression
exp1, exp2
where exp1
and exp2
are any two expressions. This will evaluated in two steps:
exp1
is evaluated and its value discarded. exp2
is evaluated and its value is the value of entire expression. NOTE: Evaluating exp1
should always have a side effect; if it does not, then exp1
serves no purpose.
In your case
if(i=55,0,10,0)
i=55
is evaluated first and its value discarded (but side effect to i
has been done, i.e, 55
is assigned to i
). 0
evaluated then and discarded. 10
evaluated then and discarded. After then right most 0
is evaluated and it will be the value of entire expression ((but not the value of sub-expressions)) in if
condition and make the condition false.
But side effect to i
has been done and that's why you are getting output as55
.
Upvotes: 3
Reputation: 8946
The comma operator is left to right.
You have values: 55,0,10,0
and the right-most value is 0
that means false
.
Also assignment operator has higher priority then comma, so i
is set to 55
.
Upvotes: 0