Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of unsigned int in C

Tags:

c

int

unsigned

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

like image 988
user3437460 Avatar asked Dec 19 '22 09:12

user3437460


2 Answers

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.

like image 156
bitcell Avatar answered Dec 21 '22 21:12

bitcell


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.

like image 40
SzG Avatar answered Dec 21 '22 21:12

SzG