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/expression rearrangement (2nd summary) Message-ID: <1991May27.113628.26880@ucthpx.uct.ac.za> Date: 27 May 91 11:36:28 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: 56 Responses are still flowing in to my question. I have had two that are quite explicit, so I thought I would post them as a refinement on the previous summary. From: worley@compass.COM i) Does ANSI C say that compilers can rearrange the order of expression evaluation? To a certain extent -- see section 3.3 of the standard and the accompanying rationale document. The key point is that the dataflow between the operators can't be changed, but the order in which the operators is executed can be changed (as long as each value is computed before it is consumed!). For example, in "a*b + c*d", the compiler may perform the two multiplications in any order, but in "a + b + c", the first addition must be performed before the second, because it associates as "(a + b) + c", showing that the second addition has as an argument the result of the first. ii) Does it say that Boolean expressions must be evaluated with short- circuit evaluation? The && and || operators are required to be short-circuited -- see sections 3.3.13 and 3.3.14 of the standard. The &, |, and ^ operators are required to not be short-circuited -- see sections 3.3.10-12 of the standard. =================================================================== From: der Mouse > i) Does ANSI C say that compilers can rearrange the order of > expression evaluation? In general, yes. There are a few exceptions; notably, the &&, ||, ?:, and , operators promise some things about the order in which their operands are evaluated (and in some cases, about whether certain operands are evaluated at all). > ii) Does it say that Boolean expressions must be evaluated with > short-circuit evaluation? When using the short-circuit operators && and ||, yes. > We think the answers to both of these are yes, but we aren't sure. Mostly. The second one is yes; the first one is a qualified yes. =================================================================== Thanks again folks - the question is certainly resolved (and I can go back to writing `if (ptr && ptr->next)...' 8-) ) 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