Integer division
Shack Toms
jst at abic.UUCP
Thu Feb 6 11:19:40 AEST 1986
> By the way, Tom Duff, have YOU ever seen an example where a%b<0 is preferred?
I am squarely in the 0<=a%b<b camp. I don't believe I have ever
used a mod function on signed integers when it was not "corrected"
with that obnoxious "if (a<0) a+=b".
However: One might use a%b<0 iff a<0 in an algorithm which printed
the value of an integer in a given radix. The least significant
digit of a in radix b would then be |a%b|. :-)
Note: K&R allows the definition of a%b to take on either of two
values, when a<0 or b<0. This means that, even on the rare (in my
experience) algorithm which requires a%b<0 iff a<0, the programmer
will have to add extra code to compensate for implementations which
always return a non-negative modulus.
It is the *ambiguity* in the specification which is most disconcerting.
Perhaps K&R thought that the performance penalty of implementing a
consistent modulus (or divide) was not justified, since negative
integers are rarely encountered in "C" [this comment cannot be traced
to K&R.] However, this performance penalty can be avoided simply by
declaring unsigned integers as "unsigned int". The way the definition
is now, one cannot portably take advantage of either implementation
of divide. That is: even on machines which implement modulus
according to the whims of the particular net.flame(r) [:-)], the
overhead of either:
m = a%b;
if (m<0) m += b;
or:
m = a%b;
if (a<0 && m>0) m -= b;
is always incurred in portable code. (Unless your compiler is
more intelligent than any of the "C" compilers I have ever used.)
On the other hand: the lack of the property
-a/b == -(a/b)
Is easily accounted for portably (simply write the expression you
mean rather than the other one. :-))
Disclaimer: blah blah blah....
Shack Toms
More information about the Comp.lang.c
mailing list