Possible Duplicate:
How do promotion rules work when the signedness on either side of a binary operator differ?
I'm trying to wrap my head around integer promotion and overflow in C++. I'm a bit confused with several points:
a) If I have the following code segment:
int i = -15;
unsigned j = 10;
std::cout << i + j;
I get out -5 % UINT_MAX
. Is this because the expression i + j
is automatically promoted to an unsigned? I was trying to read the standard (4.13):
— The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.
I'm not sure if I'm reading this incorrectly, but if that is true, why is i + j
ending up as unsigned?
b) Adding onto the previous segment, I now have:
int k = j + i;
That is getting evaluated to -5
. Shouldn't the expression j + i
be evaluated first, giving 4294967291
on my system, and setting that equal to j? That should be out of bounds, so is this behavior undefined? I'm not sure why I get -5
.
c) If I change the segment from a) slightly using short
, I have:
short i = -15;
unsigned short j = 10;
std::cout << i + j;
I figured when I did this, I would get the same result as a), just with -5 % USHRT_MAX
. However, when I execute this, I get -5
. Why does using short
give a different value than int
?
d) I have always learned that the overflow behavior of a signed integral is undefined. For example: int r = ++INT_MAX
would be undefined.
However, if there was an unsigned overflow, the quantity would be defined. For example: unsigned a = ++UINT_MAX
, then a would be 0
. Is that correct?
However, the standard didn't seem to say anything about it. Is that true? If so, why is that?