what's the point using unsigned int in C?

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: