Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the point using unsigned int in C?

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?

like image 454
Danny Avatar asked Dec 22 '18 22:12

Danny


People also ask

What is the point of using unsigned int?

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.

Is unsigned int better to use?

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).

Why we use signed and unsigned in C?

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.


1 Answers

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.

like image 123
Stephan Lechner Avatar answered Oct 02 '22 05:10

Stephan Lechner