Two Birds with One Stone
Ron Natalie <ron>
ron at brl-sem.ARPA
Sat Jan 4 07:15:20 AEST 1986
> In article <864 at kuling.UUCP> thomas at kuling.UUCP (Thomas H{meenaho) 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.
> >However most useable processors provide arithmetic shifts which will give
> >the right result even if it is a signed divide.
>
> Ok, try this program:
>
> main()
> {
> printf("-3/2 = %d\n-3 >> 1 = %d\n",(-3)/2,(-3) >> 1);
> }
>
> I think you'll find the results are different, even when the compiler
> does an arithmetic right shift! (The difference is the direction in
> which rounding occurs.)
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
.
More information about the Comp.lang.c
mailing list