Short circuit evaluation (summary)

Graham Wheeler gram at uctcs.uucp
Fri May 24 23:17:31 AEST 1991


I've had several responses to the question I posted, one or two of them
being no help at all and just short of abusive. I guess I phrased things
a bit badly, as only one response actually had an answer to the *real*
question. To recap, I wanted to know what ANSI C specified about 
	
	i) short circuit evaluation of Boolean expressions
	ii) order of evaluation of expressions

I was 99% sure that C used short circuit evaluation (thanks to those 
who confirmed this, anyway). My real question, and one which is relevant
to me as I teach a compiler course, was:

  If short circuit evaluation is allowed, can the compiler still
  rearrange expressions? If so, a check like:

	if (p && p->next)...

  could cause a segmentation violation if p is NULL, *IF* the compiler
  rearranged the expression so that the p->next was tested first.

In practice, a compiler that rearranges expressions will usually do so by
putting the cheaper expression first, especially if short circuit evaluation
is supported. The issue is that in C expressions may have side effects (by
that I include the possibility of a segmentation violation 8-) ) and so the
consequences of such a rearrangement may be serious.

All but one seemed to miss this point. The logical answer is no, the compiler
must evaluate Boolean expressions in the same order as specified in the source
program.

The two most useful responses I got were:

=========================================================================
From: Xing Wu <wuxing at comp.mscs.mu.EDU>

In article <1991May22.092404.25297 at ucthpx.uct.ac.za> you write:
>ii) Does it say that Boolean expressions must be evaluated with short-
>	circuit evaluation?

Yes.  Take a look at A7.14 and A7.15 in K&RII (pages 207-8 in my copy).
=========================================================================

and, more pertinently:

=========================================================================
From: Richard Flamsholt S0rensen <richard at iesd.auc.DK>

  C has *always* guaranteed short-circuit evaluation - you may safely
use the practice "if (ptr != NUL && ptr->next ...) ..". This also
implies, that it will *never* rearrange expressions.
=========================================================================

Thanks to those who responded. No thanks to those who were insulting.
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