Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

c - unsigned char output of a signed char

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...