From K&R second edition (circa 1988)
The binary /
operator yields the quotient, and the %
operator the
remainder, of the division of the first operand by the second; if the
second operand is 0, the result is undefined, Otherwise, it is always
true that (a/b)*b + a%b
is equal to a
. If both operands are
non-negative then the remainder is non-negative and smaller than the
divisor; if not, it is guaranteed only that the absolute value of the
remainder is smaller than the absolute value of the divisor.
For example, to compute -8/-5
(under the C89 rules), we first need to compute -8%-5
. The specification allows two possible answers for the remainder: -3
and 2
. Both satisfy the requirement that the absolute value of the remainder is smaller than the absolute value of the divisor, and both satisfy the requirement that (a/b)*b + a%b
equals a
.
(-8/-5)*-5 + -3 = -8 ==> (-8/-5) = 1 since (1)*-5 + -3 = -8
(-8/-5)*-5 + 2 = -8 ==> (-8/-5) = 2 since (2)*-5 + 2 = -8
So the result of division was allowed (by C89) to have two different answers, because (assuming negative a
or b
) the result of the remainder operator %
could either be negative or positive. This was fixed in C99, which requires division to truncate towards 0.
For those more mathematically inclined, note that
-3 ≣ 2 mod(5)
https://en.wikipedia.org/wiki/Congruence_relation