I'll consider the following snippet :
int a =-9;
int m = 10;
unsigned int m1 =10;
std::cout<<a%m<<std::endl;
std::cout<<a%m1<<std::endl;
the result is :
-9
7
The 7 is so strange. Can anyone have an explanation to it ?
I'll consider the following snippet :
int a =-9;
int m = 10;
unsigned int m1 =10;
std::cout<<a%m<<std::endl;
std::cout<<a%m1<<std::endl;
the result is :
-9
7
The 7 is so strange. Can anyone have an explanation to it ?
Per C++ 2017 (draft n4659) 8 11, the usual arithmetic conversions are performed on the operands of a % m
. Per 11.5.3, when one operand has signed integer type and the other has unsigned integer type of greater or equal rank, the signed operand is converted to the type of the unsigned operand.
This causes the int
value of −9 to be converted to unsigned
. This conversion performed modulo one more than the maximum value of unsigned
, which is apparently 4,294,967,295 (232−1) in your implementation, so the conversion is performed modulo 4,294,967,296, which produces 4,294,967,287. (Performing a conversion modulo 4,294,967,296 means that 4,294,967,296 is added or subtracted as many times as needed to produce a result in the range from 0 to 4,294,967,295, inclusive.)
Then the %
operator operates in the usual way; the remainder of dividing 4,294,967,287 by 10 is 7.