Behavior of unsigned int in C

半腔热情 提交于 2019-12-10 17:20:07

问题


The size of an unsigned int in C is 0 to 65,535 or 0 to 4,294,967,295.

I tested with the following codes in C:

unsigned int number = 0;
number -= 300;
printf("%d\n", number);

OUTPUT: -300

I remember that if the value of unsigned int variable goes below 0, it should wrap around and I was expecting the output to be something like 4294966996. However the output printed from the console is -300.

I tested similar statements in C++, it does give me 4294966996.

My question is: Why is the output -300 despite the fact that it is an unsigned int?


PS: I've looked through several posts with similar title, but they are not addressing the same issue:

signed vs unsigned int in C

Unexpected results on difference of unsigned ints


回答1:


Because printf("%d\n", number); will print a signed value, even if the parameter is unsigned. Use printf("%u\n", number); for an unsigned value to be correctly printed.




回答2:


Just a bit of background to @UniCell's excellent answer.

The hardware stores an int and an unsigned int in exactly the same way. No difference. If you start adding to or subtracting from them, they will overflow and underflow in exactly the same way.

0xFFFFFFFF + 1 = 0
0 - 1 = 0xFFFFFFFF

If we consider the result as unsigned, 0xFFFFFFFF means 4,294,967,295, otherwise it means -1. It's called 2's complement storage. Adding and subtracting are sign-agnostic. But multiplication and division are not, so there are usually different signed and unsigned machine instructions for these.

The type of these variables is only known for the compiler, not in runtime. printf's parameters can be of any type, and the variables passed do not carry type-information in runtime. So you have to tell printf in the format string how to interpret them.



来源:https://stackoverflow.com/questions/27055983/behavior-of-unsigned-int-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!