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

后端 未结 7 1919
一个人的身影
一个人的身影 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条回答
  • 2021-01-30 07:04

    Using unsigned types to represent non-negative values...

    • is more likely to cause bugs involving type promotion, when using signed and unsigned values, as other answer demonstrate and discuss in depth, but
    • is less likely to cause bugs involving choice of types with domains capable of representing undersirable/disallowed values. In some places you'll assume the value is in the domain, and may get unexpected and potentially hazardous behavior when other value sneak in somehow.

    The Google Coding Guidelines puts emphasis on the first kind of consideration. Other guideline sets, such as the C++ Core Guidelines, put more emphasis on the second point. For example, consider Core Guideline I.12:

    I.12: Declare a pointer that must not be null as not_null

    Reason

    To help avoid dereferencing nullptr errors. To improve performance by avoiding redundant checks for nullptr.

    Example

    int length(const char* p);            // it is not clear whether length(nullptr) is valid
    length(nullptr);                      // OK?
    int length(not_null<const char*> p);  // better: we can assume that p cannot be nullptr
    int length(const char* p);            // we must assume that p can be nullptr
    

    By stating the intent in source, implementers and tools can provide better diagnostics, such as finding some classes of errors through static analysis, and perform optimizations, such as removing branches and null tests.

    Of course, you could argue for a non_negative wrapper for integers, which avoids both categories of errors, but that would have its own issues...

    0 讨论(0)
提交回复
热议问题