Expression sequencing query
Tony Williams
asw at tony.UUCP
Tue Oct 21 03:32:28 AEST 1986
In article <11900001 at maggot> barada at maggot.applicon.UUCP writes:
>> > a = ((b=1),b) + ((b=2),b) + ((b=3),b)
>
>I rearraged the above to
>
> a = (b,(b=1)) + (b,(b=2)) + (b,(b=3));
this isn't a rearragement (sic), but a different statement.
>
>And my BSD4.2 VAX produced:
>
> movl $1,_b
> movl _b,r0
> movl $2,_b
> movl _b,r1
> addl2 r1,r0
> movl $3,_b
> movl _b,r1
> addl2 r1,r0
> movl r0,_a
>
>As you can see, the comma operator is evaluated right to left. I think that
No, it is not.
>this is a serious bug.
Ah yes, but the bug is in your code, not the compiler.
>
>BTW, this code produces the proper answer of 6.
>
There is no single proper answer.
The comma operator is defined to evaluate the left operand, discard it,
then evaluate the right operand, and return the resulting value, ie
that of the RIGHT operand. So,
(b,b=1)
evaluates b and discards it, evaluates b=1, assigning one to b, and returns
the result which is the new value of b. Your statement is therefore
equivalent to
a = (b=1) + (b=2) + (b=3);
which is equiivalent to
a = 1 + 2 + 3;
followed or preceded by the assignements to b in ANY order.
The compiler has elided the evaluations of b, as the result is to be
discarded and there are no side-effects.
In summary, the compiler *is* allowed to reorder operands of operators
like +, but you are *not* allowed to reorder the operands of ","
and expect the same result.
---------------------------------------------------------------------------
Tony Williams |Informatics Division
UK JANET: asw at uk.ac.rl.vd |Rutherford Appleton Lab
Usenet: {... | mcvax}!ukc!rlvd!asw |Chilton, Didcot
ARPAnet: asw%vd.rl.ac.uk at ucl-cs.arpa |Oxon OX11 0QX, UK
More information about the Comp.lang.c
mailing list