Expression sequencing query

barada at maggot.applicon.UUCP barada at maggot.applicon.UUCP
Sun Sep 28 12:26:00 AEST 1986

/* Written  4:08 pm  Sep 24, 1986 by cullvax.UUCP!drw in maggot:net.lang.c */
> In article <760 at oakhill.UUCP> tomc at oakhill.UUCP (Tom Cunningham) writes:
> >	/* a = b + b + b */
> >	a = ((b=1),b) + ((b=2),b) + ((b=3),b)
> >
> >I expected the result to be 6.  With the Microsoft C compiler and the
> >compiler on the Sun 3, the result is 9.  Apparently the parenthetical
> >assignments are all getting done before the comma and addition.  Any
> >thoughts on this?

Harbison&Steele (7.11) makes it clear that an implementation must
evaluate one argument of a binary operator completely before starting
evaluation of the other argument.  Thus, the result should be 6.  I
don't know what the ANSI standard says.

Dec VAX Ultrix gives 9.

Lattice C 3.00 for MS-DOS gives 7!!!  (Yes, that's "7", not a typo!)

/* End of text from maggot:net.lang.c */

I rearraged the above to

	a = (b,(b=1)) + (b,(b=2)) + (b,(b=3));

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
this is a serious bug.

BTW, this code produces the proper answer of 6.

Peter Barada                                   | (617)-671-9905
Applicon, Inc. A division of Schlumberger Ltd. | Billerica MA, 01821

UUCP: {allegra|decvax|mit-eddie|utzoo}!linus!raybed2!applicon!barada
	Sanity is yet another perversion of reality.

More information about the Comp.lang.c mailing list