Short circuit evaluation/expression rearrangement (2nd summary)

Graham Wheeler gram at uctcs.uucp
Mon May 27 21:36:28 AEST 1991


Responses are still flowing in to my question. I have had two that are quite
explicit, so I thought I would post them as a refinement on the previous
summary.

From: worley at compass.COM

   i) Does ANSI C say that compilers can rearrange the order of expression 
	   evaluation?

To a certain extent -- see section 3.3 of the standard and the
accompanying rationale document.  The key point is that the dataflow
between the operators can't be changed, but the order in which the
operators is executed can be changed (as long as each value is computed
before it is consumed!).  For example, in "a*b + c*d", the compiler
may perform the two multiplications in any order, but in "a + b + c",
the first addition must be performed before the second, because it
associates as "(a + b) + c", showing that the second addition has as
an argument the result of the first.

   ii) Does it say that Boolean expressions must be evaluated with short-
	   circuit evaluation?

The && and || operators are required to be short-circuited -- see
sections 3.3.13 and 3.3.14 of the standard.  The &, |, and ^ operators
are required to not be short-circuited -- see sections 3.3.10-12 of
the standard.

===================================================================

From: der Mouse  <mouse at thunder.McRCIM.McGill.EDU>

> i) Does ANSI C say that compilers can rearrange the order of
>    expression evaluation?

In general, yes.  There are a few exceptions; notably, the &&, ||, ?:,
and , operators promise some things about the order in which their
operands are evaluated (and in some cases, about whether certain
operands are evaluated at all).

> ii) Does it say that Boolean expressions must be evaluated with
>     short-circuit evaluation?

When using the short-circuit operators && and ||, yes.

> We think the answers to both of these are yes, but we aren't sure.

Mostly.  The second one is yes; the first one is a qualified yes.

===================================================================
Thanks again folks - the question is certainly resolved (and I can go back
to writing `if (ptr && ptr->next)...' 8-) )

Graham Wheeler <gram at cs.uct.ac.za> | "That which is weak conquers the strong,
Data Network Architectures Lab     | that which is soft conquers the hard.
Dept. of Computer Science          | All men know this; none practise it"
University of Cape Town            |		Lao Tzu - Tao Te Ching Ch.78



More information about the Comp.lang.c mailing list