What does ANSI C say about short circuit evaluation?

Robert Earl rearl at watnxt3.ucr.edu
Fri May 24 02:57:02 AEST 1991


In article <1991May22.092404.25297 at ucthpx.uct.ac.za> gram at uctcs.uucp (Graham Wheeler) writes:
 
|   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?

For the most part, yes.  K&R II, section 2.12, says "C does not
specify the order in which the operands of an operator are evaluated.
(The exceptions are &&, || ?:, and ','.)"

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

Yes.  Way back in section 1.5.4, it states: "Expressions connected by
&& or || are evaluated left to right, and it it guaranteed that
evaluation will stop as soon as the truth or falsehood is known."

|   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.

Will never happen (with a conforming compiler-- and likely with any
popular old compiler).  Isn't that good news?

I'm sure someone will gladly post an example or two of compilers that
didn't follow this, and caused some fun bugs.  :-)


--
______________________________________________________________________
			\					
 robert earl		/	"Love is a many splintered thing"
 rearl at watnxt3.ucr.edu	\		--Sisters of Mercy
 rearl at gnu.ai.mit.edu	/



More information about the Comp.lang.c mailing list