Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should unsigned ints be used if not necessary?

Tags:

Should one ever declare a variable as an unsigned int if they don't require the extra range of values? For example, when declaring the variable in a for loop, if you know it's not going to be negative, does it matter? Is one faster than the other? Is it bad to declare an unsigned int just as unsigned in C++?

To reitterate, should it be done even if the extra range is not required? I heard they should be avoided because they cause confusion (IIRC that's why Java doesn't have them).

like image 672
Celeritas Avatar asked Sep 01 '12 06:09

Celeritas


People also ask

Should you use unsigned ints?

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.

Why are unsigned integers bad?

The big problem with unsigned int is that if you subtract 1 from an unsigned int 0, the result isn't a negative number, the result isn't less than the number you started with, but the result is the largest possible unsigned int value.

Should I use unsigned int or uint32_t?

uint32_t is used when you must have a 32 bit unsigned. int or unsigned int for general purposes when you don't need a guaranteed size and unsigned only if you can ensure that you won't have negative numbers.

Why do we need signed and unsigned integer?

Unsigned can hold a larger positive value and no negative value. Unsigned uses the leading bit as a part of the value, while the signed version uses the left-most-bit to identify if the number is positive or negative. Signed integers can hold both positive and negative numbers.


1 Answers

You should use unsigned integers when it doesn't make sense for them to have negative values. This is completely independent of the range issue. So yes, you should use unsigned integer types even if the extra range is not required, and no, you shouldn't use unsigned ints (or anything else) if not necessary, but you need to revise your definition of what is necessary.

like image 142
juanchopanza Avatar answered Oct 06 '22 23:10

juanchopanza