The importance of declaring a variable as unsigned

前端 未结 14 3344
臣服心动
臣服心动 2021-02-20 05:55

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

14条回答
  •  借酒劲吻你
    2021-02-20 06:42

    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.

提交回复
热议问题