# Modulus of a negative number

Discussion in 'C Programming' started by Jim Hunter, Feb 23, 2005.

1. ### Jim HunterGuest

Hello all,

I have been reading K&R2, and it says that "the sign of the result for % [is]
machine-dependent for negative operands." Does this mean that the absolute
value of the result is guaranteed, but the sign isn't? Or does it mean that
(for example) -100 % 3 == -1 on some machines and 2 on others? The latter
behavior seems illogical to me, but I've been unable to find a definitive

Thanks in advance for satisfying my curiosity and for taking mercy on a
newsgroup newbie.

Jim

Jim Hunter, Feb 23, 2005

2. ### Walter RobersonGuest

:I have been reading K&R2, and it says that "the sign of the result for % [is]
:machine-dependent for negative operands." Does this mean that the absolute
:value of the result is guaranteed, but the sign isn't?

No.

: Or does it mean that
for example) -100 % 3 == -1 on some machines and 2 on others?

Yes.

: The latter
:behavior seems illogical to me, but I've been unable to find a definitive

How were you thinking it could work with the absolute value being right but
the sign possibly being wrong? A positive value for % means that many
from the beginning; a negative value for % means that many from the end.
When the result isn't exactly half-way inbetween, changing the sign gives
a dfiferent meaning.

Walter Roberson, Feb 24, 2005

3. ### Peter NilssonGuest

No. C89 gives an implementation two options if either operand to / (or
%)
are negative: round up, or round down (this includes round to zero
which
is _required_ by C99.) In either case, if the result is representable,
the following must hold...

a == (a/b)*b + (a%b)

Examples...

5 / -3 == -2 and 5 % -3 == -1
or 5 / -3 == -1 and 5 % -3 == 2
It's sometimes useful mathematically for the modulus to always be
positive.
This, and round towards zero, are the only mechanisms that you are
likely
to encounter. C89 just happens to give an implementation 8 possible
variations.

Peter Nilsson, Feb 24, 2005

Joined:
May 3, 2010
Messages:
1