int left = std::numeric_limits<int>::min();
int right = -1;
//the code below instead of give one more than int_max gives: 18446744071562067968
unsigned long long result = left * right;
I’ve tried to look up UAC but even according to UAC rules this should produce correct output. Any ideas why the result is incorrect?
It’s undefined behavior to multiply the minimum value of a signed 2’s complement
intby -1, because the result is outside the range of the type.In this case your output is consistent with the result having been -2147483648, i.e. the overflow appears to have wrapped around. You cannot rely on wraparound for signed types, only unsigned types.
Assigning the result of a calculation to
unsigned long longdoes not change what type the calculation is performed in. As soon as you do the multiplication, you lose. So, convert one of the operands tounsigned long longbefore multiplying.