开发者

-250 prints as 6

I could not identify how the following program outputs 6 and -250.

#include<stdio.h>

int main()
{
    unsigned char p=-250;
    printf("%d",p);
    unsigned int p1=-250;
    printf("%d",p1);
    return 0;
}

Being an unsigned开发者_开发技巧 integer it has to output only the positive values.How does the p value outputs 6? Please help me understand.


printf is not typesafe. It prints whatever you ask it to, and %d says "signed integer". It is your responsibility to provide a varibale of matching type. Since the unsigned char is only 8 bits wide, the literal -250 wraps around to +6, which remains +6 when interpreted as a signed integer. Note that char and short int (and their signed/unsigned counterparts) all get promoted to int-types when passed via variadic arguments.


By default, integer numerals such as -250 have a type int. Also, negative values stores in memory in Two's complement form. Let calculate two's complement form of -250 (see Making two's complement form paragraph in wiki):

  1. Positive 250 is a 11111010 (first 8 bits, leading zeros are omitted)
  2. Complement it and get 00000101 (first 8 bits, leading ones are omitted)
  3. Add one and get 00000110 (first 8 bits, leading ones are omitted)

Type conversion rules for integer types in C says that we should drop left bits to get 8-bit char. For more details look K&R A.6.2 (well, it is for russian edition, maybe in original book it has another place).

So unsigned char p gets exactly a 00000110 value (6 in decimal). That is why you get 6 in output.

I think, you understand now why there is -250 in second printf ;)


unsigned char may consist only of numbers 0..255 numbers are converted modulo 256. So -250 casted to 6

You should not trust this behaviour. you should avoid overflow.

As of p1, it casted to unsigned int, but interpried as p1 in printf() because of %d identifier


p1 is unsigned, but the %d modifier treats the corresponding argument as signed, so even though in fact it is positive, it is printed as negative.

Whether a number is signed or unsigned is all about the representation that is applied, at the machine level it doesn't make a difference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜