The %
operator in C is not the modulo operator but the remainder operator.
Modulo and remainder operators differ with respect to negative values.
With a remainder operator, the sign of the result is the same as the sign of the dividend (numerator) while with a modulo operator the sign of the result is the same as the divisor (denominator).
C defines the %
operation for a % b
as:
a == (a / b * b) + a % b
with /
the integer division with truncation towards 0
. That’s the truncation that is done towards 0
(and not towards negative inifinity) that defines the %
as a remainder operator rather than a modulo operator.