Reputation: 166
Here is a code snippet:
unsigned short a=-1;
unsigned char b=-1;
char c=-1;
unsigned int x=-1;
printf("%d %d %d %d",a,b,c,x);
Hhy the output is this:
65535 255 -1 -1
?
Can anybody please analyze this ?
Upvotes: 1
Views: 338
Reputation: 11
Basically, you should not assign negative values to "unsigned" variables. You are trying to play tricks on the compiler, and who knows what it will do. Now, "char n = -1;" is OK because "n" can legitimently take on negative values and the compiler knows how to treat it.
Upvotes: 0
Reputation: 22311
You are printing the values using %d
which is for signed numbers. The value is "converted" to a signed number (it actually stays the same bitwise, but the first bit is interpreted differently).
As for unsigned char and short - they are also converted to 32 bit int, so the values fit in it.
Had you used %lld
(and cast the value as long long
, otherwise it could be unspecified behavior) even the last two numbers may get printed as unsigned.
Anyway, use %u
for unsigned numbers.
Bit value of 255 is 11111111
. If treated like an unsigned number, it will be 255. If treated as a signed number - it'll be -1 (the first bit usually determines sign).
When you pass the value to %d
in printf, the value is converted to a 32 bit integer, which looks like this: 00000000000000000000000011111111
. Since the first bit is 0, the value is printed simply as 255. It works similarily for your short
.
The situation is different for 32 bit integer. It is immediately assigned a 11111111111111111111111111111111
value, which stands for -1 in singed notation. And since you have used %d
in your printf, it is interpreted as -1
.
Upvotes: 6