In a C program i was trying the below operations(Just to check the behavior )
x = 5 % (-3);
y = (-5) % (3);
z = (-5) % (-3);
printf(\"%d ,%d ,%d\", x, y
According to C99 standard, section 6.5.5 Multiplicative operators, the following is required:
(a / b) * b + a % b = a
The sign of the result of a remainder operation, according to C99, is the same as the dividend's one.
Let's see some examples (dividend / divisor
):
(-3 / 2) * 2 + -3 % 2 = -3
(-3 / 2) * 2 = -2
(-3 % 2) must be -1
(3 / -2) * -2 + 3 % -2 = 3
(3 / -2) * -2 = 2
(3 % -2) must be 1
(-3 / -2) * -2 + -3 % -2 = -3
(-3 / -2) * -2 = -2
(-3 % -2) must be -1
6.5.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 integer 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, the result of the / operator is the algebraic quotient with any fractional part discarded [1]. If the quotient
a/b
is representable, the expression(a/b)*b + a%b
shall equala
.[1]: This is often called "truncation toward zero".