I thought that unsigned int could store only integers >= 0. But I tried assigning a negative to an unsigned int, nothing special happened. It seems like it stored the value with no problem.
So what is the difference between signed and unsigned int, and what's the point if it can store any value anyway?
Unsigned integers are used when we know that the value that we are storing will always be non-negative (zero or positive). Note: it is almost always the case that you could use a regular integer variable in place of an unsigned integer.
The Google C++ style guide recommends avoiding unsigned integers except in situations that definitely require it (for example: file formats often store sizes in uint32_t or uint64_t -- no point in wasting a signedness bit that will never be used).
The int type in C is a signed integer, which means it can represent both negative and positive numbers. This is in contrast to an unsigned integer (which can be used by declaring a variable unsigned int), which can only represent positive numbers.
A statement like
unsigned int t = -1;
printf("%u", t);
is completely legal and well defined in C. Negative values, when assigned to an unsigned integral type, get implicitly converted (cf. for example, this online C standard draft):
6.3.1.3 Signed and unsigned integers
(2) Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
The output of above program is an unsigned value, i.e.
4294967295
So you can assign "negative" values to unsigned integral types, yet the result is not a negative value in its actual sense. This is particularly relevant when you compare unsigned integral values to negative values. Consider, for example, the following two loops:
int i = 10;
while (--i >= 0) { // 10 iterations
printf("i: %d\n", i);
}
unsigned int u = 10;
while (--u >= 0) { // endless loop; warning provided.
printf("u: %u\n", u);
}
The first will finish after 10 iterations, whereas the second will never end: Unsigned integral values cannot become negative, so u >= 0
is always true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With