Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following code:

char x = -1;
int y = x;

printf("%u
", x);
printf("%u
", y);

The output is:

4294967295
4294967295

I dont understand why x can get such a value. I know that the maximum value of a unsigned char is 255 and for a signed char 127. How can it be 4294967295?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
203 views
Welcome To Ask or Share your Answers For Others

1 Answer

For functions like printf that use variadic arguments, any integral types smaller than an int (char and short) are implicitly promoted to int. The same is true with floating-point numbers, float is promoted to double.

Hence, your char is being sign-extended to an int with value -1, and since you are printing it as unsigned, in 2's complement you get UINT_MAX.

Edit: as chux notes below, if your char defaulted to unsigned (this depends on your compiler/platform), the answer would be 255 instead. When promotion occurs, the value will be zero-extended instead of sign-extended.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...