what happens when you use negative operators with %. example -3%2 or 3%-2
In C99 a % b has the sign of a, pretty much like fmod in math.h. This is often what you want :
unsigned mod10(int a)
{
int b = a % 10;
return b < 0 ? b + 10 : b;
}
According to Kernighan & Ritchie, 2nd edition, page 39, 2.5:
...the sign of the result for % are machine-dependent for negative operands, as is the action taken on overflow or underflow.
In C89, C90, and C++03 the standards requires only that (a/b)*b+a%b == a
for the /
and %
operators.
If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined
Edit: In C99 a negative number will be returned if the first argument is negative
In C99
-3%2=-1
3%-2=1
In C90
-3%2 or 3%-2
--> Implementation defined
The %
operator gives the remainder for integer division, so that (a / b) * b + (a % b)
is always equal to a
(if a / b
is representable; in two's complement notation the most negative integer divided by -1 is not representable).
This means that the behaviour of %
is coupled to that of /
. Prior to C99 the rounding direction for negative operands was implementation-defined, which meant that the result of %
for negative operands was also implementation-defined. In C99 the rounding for /
is towards zero (decimals are simply truncated), which also fixes the behaviour of %
in C99.