Circumspect programming (was: Evaluation of if's)

Jonathan Gingerich jon at maui.cs.ucla.edu
Fri Jun 21 08:36:03 AEST 1991


First, let's get a clear understanding of the issue, without presuming
anyone's position.

What happens with a = v?

Evaluation of a yields an address and evaluation of v yields a value.
These evaluations can interleave and interfere as in a[i] = i++;

The value is stored into the address and the value stored at the address is
the value of the expression.

The fundamental question is whether this latter sequence is one or two
independent actions.  If it is one, then

(i=1) == (i=2)

must be false.  If it is two then obviously "order of evaluation" allows
it to be true.  Let's call this question "independence of side-effects".
This question is subtle and not definitively answered under "assignment
operators" in either K&R or ANSI.  Tradition does suggest the latter
interpretation but reasonable people can disagree with whether compiler writers
received implicit permission to do this.  Many people assumed the answer
and missed the question which is why some of the discussion is so vehement.

Now ANSI has cut the Gordian knot on this issue by declaring that any
expression which writes twice or independently reads and writes a location
is "undefined".  This is something new, suggested by a decade of experience
with C.  The K&RI concept is really unspecified order of evaluation;  There
were areas which are ambiguously or not addressed, this being one.  To see a
difference, consider the statement:

if ((i=1) == (i=2)) then i=3 else i=3;

under ANSI and K&RI.

The ANSI rule is a great help, and advice to stay away from such
situations is solid.  But it is inappropriate to include references
to "sequence points" in the FAQ for comp.lang.c, especially when one
cannot even find them in K&RII;  and comp.lang.c is not reserved  for
advice on how to code - it's for explanations of C.  The original example
was not coded, but a product of a C++ compiler.

I want to thank Steve for his work developing and maintaining the FAQ.  It
is an excellent idea.  But the FAQ answer to "order of evaluation" would
be greatly improved if it clearly delineates the "independence of side-effects",
"order of evaluation", and "completion of side-effects" questions;  admits
to ambiguity in K&R and introduces the ANSI "undefined" and "sequence point"
rules as a new, clear, and better approach to the question.

Jon.

Question for ANSI folks.  Is f() + f() undefined if f() modifies a global?



More information about the Comp.lang.c mailing list