Path: utzoo!utgpu!news-server.csri.toronto.edu!bonnie.concordia.ca!thunder.mcrcim.mcgill.edu!mouse From: mouse@thunder.mcrcim.mcgill.edu (der Mouse) Newsgroups: comp.lang.c Subject: Re: What does ANSI C say about short circuit evaluation? Message-ID: <1991May25.130344.20921@thunder.mcrcim.mcgill.edu> Date: 25 May 91 13:03:44 GMT References: <1991May22.092404.25297@ucthpx.uct.ac.za> Organization: McGill Research Centre for Intelligent Machines Lines: 37 In article <1991May22.092404.25297@ucthpx.uct.ac.za>, gram@uctcs.uucp (Graham Wheeler) writes: > 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. > 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. No, this is not a danger. A compiler producing code for that example that evaluates ptr->next when ptr == 0 (ie, when ptr is a null pointer of its type) is simply broken. der Mouse old: mcgill-vision!mouse new: mouse@larry.mcrcim.mcgill.edu