So there are three values that a modulus operation can give you:
Then:
-7 % 5 = 3 (math, remainder >= 0)
-7 % 5 = -2 (C++)
-7 % (size_t)5 = 4 (C++)
Another example:
-7 % 4 = 1 (math, remainder >= 0)
-7 % 4 = -3 (C++)
-7 % (size_t)4 = 1 (C++)
When the left hand operand is positive, the answer between all three methods are the same. But for negative values they all seem to have their own methods. How is the value of modulus operations on unsigned operands calculated in C++?
This is what happens when you mix signed and unsigned values — confusion!
Now, see the bolded passage below (which assumes your
size_thas the same rank as yourint; this is always true):In short, your
-7is becomingstd::numeric_limit<size_t>::max() + 1 - 7(whatever that is on your platform), and the calculation is being performed on that value. Indeed, on my platform, that confirms the result of1.