Using distributive property to optimize.

Karl Heuer karl at haddock.ima.isc.com
Thu Feb 8 07:25:41 AEST 1990


In article <94348 at linus.UUCP> bs at linus.UUCP writes:
>[is it valid to change "n = a - (b + c);" to "n = a - b - c;"]
>
>Note also that even with integer arithmetic, the rearrangement is not
>safe. If (say) b is a large negative number and c a large positive
>number a - (b+c) may not overflow. However, a-b most certainly can.

But if, as is common, the implementation chooses to handle signed integer
overflow by producing the unique representable value which is congruent modulo
UINT_MAX+1 to the true answer, then (a-b)-c will yield the same value as
a-(b+c).  (And if the variables are unsigned integers, then the rewrite is
valid on *all* implementations, because that's how unsigned arithmetic is
defined in C.)

>Compilers should NEVER rearrange computations.

As long as they get the right answer, they may; as long as it's a desirable
performance improvement, they should.

Karl W. Z. Heuer (karl at ima.ima.isc.com or harvard!ima!karl), The Walking Lint



More information about the Comp.lang.c mailing list