Unsigned int behavior in C

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 the variable unsigned int

is below 0 it should wrap around and I expected the result to be something like 4294966996

. However, the output printed from the console is -300

.

I've tested similar statements in C ++, it gives me 4294966996

.

My question is: Why the conclusion -300

, despite the fact that it is unsigned int

?


PS: I have looked at several posts with a similar title, but they don't solve the same problem:

signed vs unsigned int in C

Unexpected results on the difference between unsigned integers

+3


source to share


2 answers


Because it printf("%d\n", number);

will print a signed value even if the parameter is unsigned. Use printf("%u\n", number);

unsigned values ​​for correct printing.



+8


source


Just a little background for @ UniCell's excellent answer.

The device stores int

and unsigned int

in the same way. No difference. If you start adding or subtracting from them, they will overflow and overflow in the same way.

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

      



Considering the result as unsigned 0xFFFFFFFF

means 4,294,967,295, otherwise it means -1. It was called a two-complement repository. Addition and subtraction are agnostic. But there is no multiplication and division, so they usually use different signed and unsigned machine instructions.

The type of these variables is only known to the compiler, not at runtime. Parameters printf

can be of any type, and passed variables do not contain run-time type information. Therefore, you must indicate printf

in the format string how to interpret them.

+2


source







All Articles