Skip your code:
short a = -5;
a = -5, which fits in short. So far so easy.
unsigned short b = -5u;
-5u means apply the unary operator to the 5u constant. 5u is (unsigned int) 5, and unary does not advance, so you get 4294967291, which is 2 ^ 32-5. (Update: I was wrong in my original answer, see Test script, which shows that this version is correct here http://codepad.org/hjooaQFW )
Now that it fits in b, it is truncated with an unsigned short (usually 2 bytes), so b = 65531, which is 2 ^ 16-5.
if( a == b )
On this line, a and b both rise to ints, so the comparison can happen correctly. If they were promoted to shorts, b would potentially turn around. If they were translated into unsigned shorts, a would potentially wrap around.
So how to say if( (int) a == (int) b ) . And a = -5, therefore (int) a = -5 and b = 65531, therefore (int) b = 65531, because ints are more shorts.
Dave
source share