Advice on unsigned int (Gangnam Style edition)

后端 未结 5 594
轻奢々
轻奢々 2021-02-02 11:38

The video \"Gangnam Style\" (I\'m sure you\'ve heard it) just exceeded 2 billion views on youtube. In fact, Google says that they never expected a video to be greater than a 32-

5条回答
  •  滥情空心
    2021-02-02 12:11

    The Google rule is widely accepted in professional circles. The problem is that the unsigned integral types are sort of broken, and have unexpected and unnatural behavior when used for numeric values; they don't work well as a cardinal type. For example, an index into an array may never be negative, but it makes perfect sense to write abs(i1 - i2) to find the distance between two indices. Which won't work if i1 and i2 have unsigned types.

    As a general rule, this particular rule in the Google style guidelines corresponds more or less to what the designers of the language intended. Any time you see something other than int, you can assume a special reason for it. If it is because of the range, it will be long or long long, or even int_least64_t. Using unsigned types is generally a signal that you're dealing with bits, rather than the numeric value of the variable, or (at least in the case of unsigned char) that you're dealing with raw memory.

    With regards to the "self-documentation" of using an unsigned: this doesn't hold up, since there are almost always a lot of values that the variable cannot (or should not) take, including many positive ones. C++ doesn't have sub-range types, and the way unsigned is defined means that it cannot really be used as one either.

提交回复
热议问题