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 i
The problem with the systematic use of unsigned
when values can't be negative isn't that Java doesn't have unsigned
, it is that expressions with unsigned values, especially when mixed with signed one, give sometimes confusing results if you think about unsigned as an integer type with a shifted range. Unsigned is a modular type, not a restriction of integers to positive or zero.
Thus the traditional view is that unsigned
should be used when you need a modular type or for bitwise manipulation. That view is implicit in K&R — look how int and unsigned are used —, and more explicit in TC++PL (2nd edition, p. 50):
The
unsigned
integer types are ideal for uses that treat storage as a bit array. Using anunsigned
instead of anint
to gain one more bit to represent positive integers is almost never a good idea. Attempts to ensure that some values are positive by declaring variablesunsigned
will typically be defeated by the implicit conversion rules.