ashna
ashna

Reputation: 7589

c modulus operator

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

Upvotes: 1

Views: 5049

Answers (5)

pcent
pcent

Reputation: 2029

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.

Upvotes: 1

Alexandre C.
Alexandre C.

Reputation: 56956

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;
}

Upvotes: 1

Arkku
Arkku

Reputation: 42109

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.

Upvotes: 1

Brian R. Bondy
Brian R. Bondy

Reputation: 347196

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

Upvotes: 3

Satish
Satish

Reputation: 1335

In C99

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

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

Upvotes: 3

Related Questions