I've seen this kind of question asked before, but supplied answers don't clear everything for me. When this question is posted it is usually accompanied by next example:
#include <iostream>
int main()
{
unsigned int u = 10;
int i = -42;
std::cout << i + i << std::endl;
std::cout << i + u << std::endl;
return 0;
}
Output:
-84
4294967264
All works as expected int is converted to unsigned. But if absolute value of i
is less than u
it seems like no such conversion is hapenning.
#include <iostream>
int main()
{
unsigned int u = 10;
int i = -3;
std::cout << i + i << std::endl;
std::cout << i + u << std::endl;
return 0;
}
Output:
-6
7
I haven't seen any answer mentioning it and can't find any explanation. Even though it seems like a logical thing to happen I havent thing any explanation accounting for this.
After:
unsigned int u = 10;
int i = -3;
the evaluation of i + u
proceeds by first converting i
to unsigned int
. For a 32-bit unsigned int
, this conversion wraps modulo 232, which is 4,294,967,296. The result of this wrapping is −3 + 4,294,967,296 = 4,294,967,293.
After the conversion, we are adding 4,294,967,293 (converted i
) and 10 (u
). This would be 4,294,967,303. Since this exceeds the range of a 32-bit unsigned int
, it is wrapped modulo 4,294,967,296. The result of this is 4,294,967,303 − 4,294,967,296 = 7.
Thus “7” is printed.