Is using an unsigned rather than signed int more likely to cause bugs? Why?

后端 未结 7 1923
一个人的身影
一个人的身影 2021-01-30 06:12

In the Google C++ Style Guide, on the topic of \"Unsigned Integers\", it is suggested that

Because of historical accident, the C++ standard also uses unsi

7条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 06:50

    As stated, mixing unsigned and signed might lead to unexpected behaviour (even if well defined).

    Suppose you want to iterate over all elements of vector except for the last five, you might wrongly write:

    for (int i = 0; i < v.size() - 5; ++i) { foo(v[i]); } // Incorrect
    // for (int i = 0; i + 5 < v.size(); ++i) { foo(v[i]); } // Correct
    

    Suppose v.size() < 5, then, as v.size() is unsigned, s.size() - 5 would be a very large number, and so i < v.size() - 5 would be true for a more expected range of value of i. And UB then happens quickly (out of bound access once i >= v.size())

    If v.size() would have return signed value, then s.size() - 5 would have been negative, and in above case, condition would be false immediately.

    On the other side, index should be between [0; v.size()[ so unsigned makes sense. Signed has also its own issue as UB with overflow or implementation-defined behaviour for right shift of a negative signed number, but less frequent source of bug for iteration.

提交回复
热议问题