signed int x = -5;
unsigned int y = x;
What is the value of y
? How is this so?
The value of y
is UINT_MAX - 5 + 1
, i.e. UINT_MAX - 4
.
When you convert signed integer value to unsigned type, the value is reduced modulo 2^N, where N is the number of value-forming bits in the unsigned type. This applies to both negative and positive signed values.
If you are converting from signed type to unsigned type of the same size, the above means that positive signed values remain unchanged (+5
gets converted to 5
, for example) and negative values get added to MAX + 1
, where MAX
is the maximum value of the unsigned type (-5
gets converted to MAX + 1 - 5
).