Short circuit evaluation/expression rearrangement (2nd summary)

Mark Brader msb at sq.sq.com
Thu Jun 6 09:18:33 AEST 1991


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 at sq.com     depending on their prejudices."    -- Tim Freeman

This article is in the public domain.



More information about the Comp.lang.c mailing list