From cppreference on Usual arithmetic conversions and C++ standard
Otherwise (the signedness is different): If the unsigned type has conversion rank greater than or equal to the rank of the signed type, then the operand with the signed type is implicitly converted to the unsigned type.
-4
is signed
and 7
is size_t
which is an unsigned
type, so -4
is converted to unsigned
first and then modulus is carried out.
With that mind, if you break it down, you will immediately see what is happening:
size_t s = -4; // s = 18446744073709551612 on a 64 bit system
size_t m = 7;
std::cout << s % m << '\n'; //5
The results might be different for a 32-bit system.
cout << -4 % 7 << endl;
still prints -4
. Why? It's because the type of both -4
and 7
is int
.
C++ standard §5.13.2.3 Type of an integer literal
The type of an integer-literal is the first type in the list in Table 8 corresponding to its optional integer-suffix in which its value can be represented. An integer-literal is a prvalue.
Table 8: Types of integer-literals without suffix:
int
long int
long long int
So, -4
and 7
both are int
in this case and hence the result of modulo is -4
.