Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!dali.cs.montana.edu!uakari.primate.wisc.edu!zaphod.mps.ohio-state.edu!cis.ohio-state.edu!tut.cis.ohio-state.edu!ucbvax!pasteur!dog.ee.lbl.gov!ucsd!ucrmath!rearl From: rearl@watnxt3.ucr.edu (Robert Earl) Newsgroups: comp.lang.c Subject: Re: What does ANSI C say about short circuit evaluation? Message-ID: Date: 23 May 91 16:57:02 GMT References: <1991May22.092404.25297@ucthpx.uct.ac.za> Sender: news@ucrmath.ucr.edu Organization: (EVIL!) Lines: 42 In-reply-to: gram@uctcs.uucp's message of 22 May 91 09:24:04 GMT In article <1991May22.092404.25297@ucthpx.uct.ac.za> gram@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@watnxt3.ucr.edu \ --Sisters of Mercy rearl@gnu.ai.mit.edu /