Is it important to declare a variable as unsigned if you know it should never be negative? Does it help prevent anything other than negative numbers being fed into a function th
It won't prevent negative numbers from being fed into a function; instead it will interpret them as large positive numbers. This may be moderately useful if you know an upper bound for error checking, but you need to do the error checking yourself. Some compilers will issue warnings, but if you're using unsigned types a lot there may be too many warnings to deal with easily. These warnings can be covered up with casts, but that's worse than sticking to signed types only.
I wouldn't use an unsigned type if I knew the variable shouldn't be negative, but rather if it couldn't be. size_t
is an unsigned type, for example, since a data type simply can't have negative size. If a value could conceivably be negative but shouldn't be, it's easier to express that by having it as a signed type and using something like i < 0
or i >= 0
(these conditions come out as false
and true
respectively if i
is an unsigned type, regardless of its value).
If you're concerned about strict Standard conformance, it may be useful to know that overflows in unsigned arithmetic are fully defined, while in signed arithmetic they're undefined behavior.
A counter argument to using unsigned
is that you may find yourself in very reasonable situations where it gets awkward and unintentional bugs are introduced. Consider a class—for example a list class or some such—with the following method:
unsigned int length() { ... }
Seems very reasonable. But then when you want to iterate over it, you get the following:
for (unsigned int i = my_class.length(); i >= 0; --i) { ... }
Your loop won't terminate and now you're forced to cast or do some other awkwardness.
An alternative to using unsigned
is just to assert
that your values are non-negative.
Reference.