Possible Duplicate:
signed to unsigned conversion in C – is it always safe?
Let’s say I declare a variable of type unsigned int : unsigned int x = -1;
Now -1 in two’s complement (assuming 32 bit machine) is 0xFFFFFFFF.
Now when I assigned this value to x, did the value 0x7FFFFFFF get assigned to x?
If it were so, then printf (“%d”,x); would have printed the decimal equivalent of 0x7FFFFFFF, right? But, clearly this isn’t happening, as the value that gets printed is -1. What am I missing here?
Edit: I know that we can use the %u format specifier to print unsigned values.
But that doesn’t help answer the question above.
The
"%d"format is for (signed) int values. If you use it with an unsigned value, it could print something other than the actual value. Use"%u"to see the actual value, or%xto see it in hexadecimal.In the declaration
the expression
-1is of type int, and has the value -1. The initializer converts this value from int to unsigned int. The rules for signed-to-unsigned conversion say that the value is reduced moduloUINT_MAX + 1, so-1will convert toUINT_MAX(which is probably0xffffffffor4294967295ifunsigned intis 32 bits).You simply cannot assign a negative value to an object of an unsigned type. Any such value will be converted to the unsigned type before it’s assigned, and the result will always be >= 0.