Newsgroups: comp.lang.c Path: utzoo!sq!msb From: msb@sq.sq.com (Mark Brader) Subject: Re: Short circuit evaluation/expression rearrangement (2nd summary) Message-ID: <1991Jun5.231833.20542@sq.sq.com> Summary: "As if" rule explained more precisely Organization: SoftQuad Inc., Toronto, Canada References: <16283@smoke.brl.mil> <1991Jun3.222214.20948@zoo.toronto.edu> Date: Wed, 5 Jun 91 23:18:33 GMT Lines: 63 Wow, I get to correct Henry Spencer. > > [a + b + c] > > What you DO know: The addition of a and b will be made before c is > > added to the result. > > More precisely, what you know is that the program will *behave as if* things > were done that way. In particular, if the compiler can be sure that the > order of evaluation will not affect behavior, it can use any order it pleases. Still more precisely, what you know is that *if* the program would *not* cause an exception (e.g. overflow) if things were done that way, *then* it will behave *as if* things were done that way. Presuming that i and j are ints which are 16 bits long, the statement i = 20000 + 20000 + j; causes undefined behavior, since 20000+20000 causes int overflow. However, since the behavior *is* undefined, the compiler is free to ignore the "as if" rule and compile the statement in some other way, e.g. as if it read printf ("This is silly, but legal\n"); or, more practically, as if it read i = 20000 + (20000 + j); which *is* valid for some values of j (e.g. -20000). On the other hand, if the statement originally read i = 20000 + (-20000) + j; then the compiler would *not* be free to compile it as if it was i = 20000 + ((-20000) + j); unless int overflows are ignored and cause wraparound in the common manner. In this example, the rewritten form could cause an overflow where the original form could not; in my first example, the reverse is true. These examples were contrived to match the a+b+c of the earlier messages; here is a practical example. long p; extern short q, r; p = q * r; which, I hear, is compiled on some systems as if it was written p = q * (long) r; which is probably what the writer meant to say in the first place. Again, this rewriting is legal because it cannot *cause* an exception and it produces the same result if no exception would have occurred. -- Mark Brader "People tend to assume that things they don't know SoftQuad Inc., Toronto about are either safe or dangerous or useless, utzoo!sq!msb, msb@sq.com depending on their prejudices." -- Tim Freeman This article is in the public domain.