Should unsigned ints be used if not necessary?

前端 未结 7 1061
醉梦人生
醉梦人生 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:24

    Even if you have variables that should only take non negative values unsigned can be a problem. Here is an example. Suppose a programmer is asked to write a code to print all pairs of integer numbers (a,b) with 0 <= a < b <= n where n is a given input. An incorrect code is

    for (unsigned b = 0; b <= n; b++)
       for (unsigned a=0; a <=b-1; b++)
           cout << a << ',' << b << n ;
    

    This is easy to correct, but thinking with unsigned is a bit less natural than thinking with int.

提交回复
热议问题