Expression sequencing query

Joseph S. D. Yao jsdy at hadron.UUCP
Sat Sep 27 15:47:51 AEST 1986


In article <111 at titan.UUCP> eectrsef at titan.UUCP (Sean Eric Fagan - SA User Serv.) writes:
>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.
plus other comments tsk-tsk'ing this, etc.

X3J11 states that subexpressions may be evaluated in any [presumably
valid-jsdy] order, even if they produce side effects.  The order in
which side effects take place is unspecified.  Side effects only
have to be complete at what X3J11 calls "sequence points."  The
comma operator  i s  (in my [old] version) a sequence point, and the
standard seems to require that at each comma, the left operand be
evaluated and then the right, and the result be the latter.  The
example bears this out; but it is not as complicated as the above.
Addition is not called a sequence point.

HOWEVER

As has been said before, X3J11 has little or nothing to do with
contemporary C compilers.  It hasn't even been issued yet!  Not
in final form.  (So if the salesman knocks on your door with an
"ANSI C compiler," slam it!)  The bible has been K&R, which says
specifically in the sections on Precedence and Order of Evaluation
(K&R 2.12, Ref. 7.) the first two sentences above, plus:
"When side effects (...) takes [sic] place is left to the discretion
of the compiler, ...
"... writing code which depends on order of evaluation is a bad
programming practice in any language."

Guy & Steele, although slightly influenced by X3J11, echo:
(7.11) "It is, of course, bad programming style to have two side
effects on the same variable in the same expression, because the
order of the side effects is not defined; but the all-too-clever
programmer here has reasoned that the order of the side effects
doesn't matter, ..."

It looks like your C compiler decided to evaluate all the lefts
of the commas first, then the rights.  For what it's worth, this
resembles what G&S call "interleaving", which they deprecate in
the evaluation of function arguments.  (But not explicitly in
this case.)  Also for what it's worth, I would have hoped that
the compiler did what you thought.  HOWEVER (again), I've learned
that where the document doesn't explicitly specify some part of
the language, the definition of the language (for all practical
purposes) resides in the compiler.
-- 

	Joe Yao		hadron!jsdy at seismo.{CSS.GOV,ARPA,UUCP}
			jsdy at hadron.COM (not yet domainised)



More information about the Comp.lang.c mailing list