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