tags:

views:

74

answers:

5
+1  Q: 

c modulus operator

what happens when you use negative operators with %. example -3%2 or 3%-2

+1  A: 

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

Brian R. Bondy
In C99, Result has the same sign as dividend
Satish
+1  A: 

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.

Arkku
A: 

In C99

-3%2=-1
 3%-2=1

In C90 -3%2 or 3%-2 --> Implementation defined

Satish
A: 

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;
}
Alexandre C.
+1  A: 

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.

pcent
Satish
@Satish, I agree, it would be better, but as long as I know the standards are commercial, and I don't have a copy of it. The answer provided by Brian R. Bondy is based on the standards, and you completed it with your comment.
pcent