Two Birds with One Stone

Walter Bright bright at dataioDataio.UUCP
Wed Jan 8 04:17:36 AEST 1986


In article <615 at brl-sem.ARPA> ron at brl-sem.ARPA (Ron Natalie <ron>) writes:
>> >In article <874 at dataioDataio.UUCP> bright at dataio.UUCP (Walter Bright writes:
>> >>Almost but not quite true. A compiler CANNOT normally replace a divide
>> >>by a right-shift if it is an integer divide. This is because a right
>> >>shift of a negative integer is not the same as a divide.
>
>Actually, K&R states that the truncation from an integer divide of negative
>numbers is machine dependant -3/2 could correctly be -2 or -1 depending on
>the machine.  The only guarantee that they make is that
>
>	(a/b)*b + a%b must be equal to a

You are correct. However, the point is that on most machines the DIVIDE
instruction works one way, and the ARITHMETIC_RIGHT_SHIFT works another
way. If the compiler replaces a divide with a right shift, it is WRONG
if in doing so it changed the result of the computation. That is, the
following two pieces of code better produce the same result:

	k = -3;
	i = 2;
	j = k/i;

	k = -3;
	j = k/2;



More information about the Comp.lang.c mailing list