order of evaluation of expression

Harald Eikrem harald at kvvax4.UUCP
Thu Oct 16 08:39:40 AEST 1986


dave at murphy.UUCP (Dave Cornutt) writes:
>Well, gang, I just tried this code on our Gould UTX/32 C compiler:
>
>main()
>{
>	int a=0, b=0;
>	a = ((b=1),b) + ((b=2,b) + ((b=3),b);
>	printf("%d %d\n",a,b);
>	a = (b=1) + (b=2) + (b=3);
>	printf("%d %d\n",a,b);
>}
>
>and got:
>
>9 3
>6 3

With the Ultrix 1.1 (BSD4.2) compiler you would have seen:
9 3
7 3

Explain anyone?

Case 1 is demonstrated by:
	int a,b,c,d,e;
	a = (b=1,c=b) + (b=2,d=b) + (b=3,d=b);
	printf("%d %d %d %d %d\n",a,b,c,d,e);

9 3 3 3 3

To me, it turns more weird if I say:
	a = (b=1,c=b,b) + (b=2,d=b,b) + (b=3,e=b,b);
	printf("%d %d %d %d %d\n",a,b,c,d,e);

and out comes:
9 3 1 2 3

Parentheses to pair expressions around comma operators make no difference.


>The real moral of this story is that you shouldn't do more than one assignment
>to a variable in an expression, and you shouldn't use the assigned-to variable
>elsewhere in the expression (although using the expression value of the
>assignment is okay).  The same applies to ++, --, and function calls.

Clearly.
-- 

   ...!mcvax!kvvax4!harald      -=-=-=-=<  Harald E  >=-=-=-=-



More information about the Comp.lang.c mailing list