Integer division

Shack Toms jst at abic.UUCP
Wed Feb 19 06:17:03 AEST 1986


> [ Thomas Spencer writes...]
> There is of course, always another way to look at it.  The '%' operator
> is not defined to be MOD, it is defined such that
> 	(a/b)*b + a%b = a
> In other words, it is the REMAINDER upon dividing a by b.  Now, if you
> want a%b to always be positive, you must then have
> 	(-a)/b != -(a/b)
> which, I think you will agree, is much worse....

This property [(-a)/b == -(a/b)] is *not* guaranteed by the
definition of % in C.  An implementation of C is free to return
nonnegative remainders, so long as the implementation of / rounds
toward -infinity.  This property does not seem all that precious
to me, though.  Anyone who writes code which utilizes the entire
range of int soon learns not to be too cavalier with negation,
since the range of int is not always symmetric about 0.

> ...  If you really want MOD,
> here it is:
> mod(a,b)
> {
> 	return (( a % b ) + b) % b;
> }

And if you really want quotients to round toward 0 and negative remainders
[although I believe this is desired less frequently] you had better write
those too.



More information about the Comp.lang.c mailing list