🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: net.lang.c
Article #9627

Re: Expression sequencing query

#9627
From: Tony Williams
Date: Mon, 20 Oct 1986 17:32
56 lines
2412 bytes
In article <11900001@maggot> barada@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@uk.ac.rl.vd			|Rutherford Appleton Lab
Usenet:		{... | mcvax}!ukc!rlvd!asw	|Chilton, Didcot
ARPAnet:	asw%vd.rl.ac.uk@ucl-cs.arpa	|Oxon OX11 0QX, UK
Technical Details
Message-ID: <1763@rlvd.UUCP>
Path: arc1-ca.pugleaf.net!utzoo!watmath!clyde!caip!rutgers!husc6!seismo!mcvax!ukc!warwick!rlvd!asw
References: <111@titan.UUCP> <11900001@maggot>

Show Full Headers
Complete Article Headers
Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: arc1-ca.pugleaf.net!utzoo!watmath!clyde!caip!rutgers!husc6!seismo!mcvax!ukc!warwick!rlvd!asw
From: asw@tony.UUCP (Tony Williams)
Newsgroups: net.lang.c
Subject: Re: Expression sequencing query
Message-ID: <1763@rlvd.UUCP>
Date: Mon, 20-Oct-86 13:32:28 EDT
Article-I.D.: rlvd.1763
Posted: Mon Oct 20 13:32:28 1986
Date-Received: Wed, 22-Oct-86 06:22:50 EDT
References: <111@titan.UUCP> <11900001@maggot>
Sender: news@rlvd.UUCP
Reply-To: asw@tony.UUCP (Tony Williams)
Organization: Informatics Division, R.A.L
Lines: 56