Hello All,
In the section 2.5 Arithmetic Operator of K&R2 says that "... the
sign of result for % are machine-dependent for negative operand, as
the action taken on overflow or underflow."
I have failed to understand why the sign of -2%3 or -2%-3 or 2%-3 has
to be machine dependent?
Could you please explain how the % operator behaves in C ? I
understand that in all the above case the result will be 2 if both
the number is positive. In case of negative number how it should work?
Please provide some inputs.
K&R II is based on the original ANSI C Standard of two decades
ago, and there have been some changes since. But let's begin at
the beginning ...
First, % is often called the "modulo" operator, but it might
have been better to call it the "remainder" operator. When an
integer division is inexact there is a non-zero remainder, and
this is the quantity % delivers. 6 / 3 is 2, exactly, so 6 % 3
is zero. 7 / 3 is 2, INexactly, so 7 % 3 is 1. For positive N,
Q = N / 3 is the quotient (exact or inexact) and R = N % 3 is the
amount of N "left over," not accounted for in the quotient. You
can always recover N from Q and R: N = Q * 3 + R.
But what if N is negative? If the division is exact there's
no problem: -6 / 3 is -2, exactly, so the remainder -6 % 3 is zero.
But -7 / 3 could (under ANSI C rules) be either -2 ("round toward
zero") or -3 ("round toward minus infinity"), and implementations
were allowed to produce either result. Whichever they chose to
deliver, though, they had to make N = Q * 3 + R work correctly.
So if -7 / 3 gave Q = -2, then -7 % 3 had to deliver R = -1. If
-7 / 3 yielded Q = -3, then -7 % 3 had to produce R = +2. Similar
considerations apply for 7 / -3 and 7 % -3: The implementation had
a choice of two possible quotients, but had to deliver a remainder
that made 7 = Q * -3 + R work.
The original ANSI C Standard has been revised several times,
and the C99 revision tightened the rules a bit. Specifically, it
took away the implementation's choice of which quotient to produce:
Division must now "round toward zero," always. Nowadays, -7 / 3
must produce -2 (never -3), so the remainder must be -7 % 3 = -1,
(never +2). As before, N = Q * 3 + R always holds -- but now there's
no choice about what Q and R must be.