Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!uunet!zephyr.ens.tek.com!tektronix!percy!m2xenix!quagga!ucthpx!uctcs.uucp!gram From: gram@uctcs.uucp (Graham Wheeler) Newsgroups: comp.lang.c Subject: Short circuit evaluation (summary) Message-ID: <1991May24.131731.21408@ucthpx.uct.ac.za> Date: 24 May 91 13:17:31 GMT Sender: news@ucthpx.uct.ac.za (UCT News Admin.) Reply-To: gram@uctcs.uucp (Graham Wheeler) Organization: Dept. of Computer Science, University of Cape Town Lines: 57 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 In article <1991May22.092404.25297@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 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 | "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