What does ANSI C say about short circuit evaluation?

Graham Wheeler gram at uctcs.uucp
Wed May 22 19:24:04 AEST 1991


The following question has caused a bit of debate here in the last couple of
days. There are two parts:

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

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

We think the answers to both of these are yes, but we aren't sure. This
would mean that a statement like:

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

could potentially cause a segmentation violation on a system with meory
protection if the compiler was stupid enough to try to evaluate the second
(more complex) subexpression first - ie, one cannot rely on short-circuit
evaluation to prevent this from happening.

This doesn't bother me much as I tend to write such pointer expressions as

	if (ptr) if (ptr->next) ...

for safety, but it may cause some elusive buggy behaviour.

Preferably e-mail your responses, thanks.

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