Should unsigned ints be used if not necessary?

前端 未结 7 1021
醉梦人生
醉梦人生 2020-12-15 05:38

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

7条回答
  •  攒了一身酷
    2020-12-15 06:37

    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 an unsigned instead of an int 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 variables unsigned will typically be defeated by the implicit conversion rules.

提交回复
热议问题