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
Is it important to declare a variable as unsigned if you know it should never be negative?
Certainly it is not important. Some people (Stroustrup and Scott Meyers, see "Unsigned vs signed - Is Bjarne mistaken?") reject the idea that a variable should be unsigned just because it represents an unsigned quantity. If the point of using unsigned
would be to indicate that a variable can only store non-negative values, you need to somehow check that. Otherwise, all you get is
Certainly it doesn't prevent people from supplying negative values to your function, and the compiler won't be able to warn you about any such cases (think about a negative runtime based int-value being passed). Why not assert in the function instead?
assert((idx >= 0) && "Index must be greater/equal than 0!");
The unsigned type introduces many pitfalls too. You have to be careful when you use it in calculations that can temporary be less than zero (down counting loop, or something) and especially the automatic promotions that happen in the C and C++ languages among unsigned and signed values
// assume idx is unsigned. What if idx is 0 !?
if(idx - 1 > 3) /* do something */;