modulus fn with negatives

Henry Spencer henry at utzoo.UUCP
Sun Sep 9 09:12:47 AEST 1984


The basic problem here is simple:  there is no unique way to turn a
non-integer result of integer division into a <quotient, remainder>
pair, where both quotient and remainder are integers.  There are at
least four different ways to do this (truncate quotient towards zero,
truncate toward minus infinity, truncate to give positive remainder,
rounding with some sort of tie-breaking rule).  Several of these give
the same answer when all numbers are positive, but negative numbers
expose the differences.

Fortran picked, more or less arbitrarily, truncate-towards-zero, and
many machines have followed its lead, but that's by no means universal.
Note that two's-complement arithmetic shifts implement truncate-towards-
minus-infinity division, not truncate-towards-zero.

The current draft of the ANSI C standard explicitly states that either
truncate-towards-zero or truncate-towards-minus-infinity is legitimate,
and the choice is implementation-dependent.

The only safe rule is to avoid integer division with negative operands,
unless you don't care about the rounding behavior.  Portable programs
should not depend on the rounding behavior of integer division.
-- 
				Henry Spencer @ U of Toronto Zoology
				{allegra,ihnp4,linus,decvax}!utzoo!henry



More information about the Comp.lang.c mailing list