August said:
Hi,
How come the modulus operator doesn't always yield non-negative values?
I expect e.g. (-1) % 3 to be 2 but I get -1. If I want to decrement a
cyclic variable n by k I have to write something like
n = ((n - k) % length + length) % length
where as in e.g. Pascal i can simply write
n := (n - k) MOD length
to get the desired result.
% is defined in terms of / (see below).
If / rounds down, then % yields positive values.
If / rounds to zero, you get the observed behaviour.
C89 allows both, C99 only round-to-zero.
From the last public draft of C89:
,---
3.3.5 Multiplicative operators
Syntax
multiplicative-expression:
cast-expression
multiplicative-expression * cast-expression
multiplicative-expression / cast-expression
multiplicative-expression % cast-expression
Constraints
Each of the operands shall have arithmetic type. The operands of
the % operator shall have integral type.
Semantics
The usual arithmetic conversions are performed on the operands.
The result of the binary * operator is the product of the operands.
The result of the / operator is the quotient from the division of
the first operand by the second; the result of the % operator is the
remainder. In both operations, if the value of the second operand is
zero, the behavior is undefined.
When integers are divided and the division is inexact, if both
operands are positive the result of the / operator is the largest
integer less than the algebraic quotient and the result of the %
operator is positive. If either operand is negative, whether the
result of the / operator is the largest integer less than the
algebraic quotient or the smallest integer greater than the algebraic
quotient is implementation-defined, as is the sign of the result of
the % operator. If the quotient a/b is representable, the expression
(a/b)*b + a%b shall equal a .
`---
Cheers
Michael