actually i forgot to type my query.
ya my question is regarding assignment in the two expression.
in the second expression why is i=k. why cant it be like this i=j.
thanx
This is related to both operator precedence and the value returned by the comma operator.
You could easily look both of these up in which case you would be able to tell what the value of
l = (i=j,k);
l (assuming it is another int) is in this expression.
What most people forget is how the comma operator works, it has the syntax
<expression1>,< expression2>
but it returns the value <expression2> . Now at this point you are probably about to ask if it returns the value <expression2> then how can i = j in the statement
i=j,k;
surely i should equal k if the comma operator is returning <expression2> . However both = and , are operators so the order they get evaluated in in C is dependent on their relative precedence. Looking at an operator precedence table you will quickly see that the comma operator has the lowest precedence of any operator, that is everything takes precedence over it which means that
i=j,k;
is evaluated as
(i=j),k;
which is why i = j following the statement. So coming back to my original question what is the value of l following
l = (i=j,k);
We know that i = j because of the relative operator precedence of = and , I have surrounded the expression in ( ) to force it to evaluate first (i.e. break the precedence order which is what ( and ) are for) l takes on the value of the expression
i=j,k
which we know is the second expression so l = k.
To be honest I have never come across what I would call a good use for the comma operator except in code obfuscation contests.
I had a big counter argument for why Banfa was wrong complete with research and links and whatnot and then I re-read the post and my argument evaporated. I was going to say: Oh yea, well then how do you explain the right-to-left associativity of the assignment operator in the expression
a = b = c = d = 1; since it is interpreted as (a = (b = (c = (d = 1))));
But then I noticed that you are talking about the comma between the right hand operands as in i = j,k;
I'm such a dunce some times :(
Comment