关于 unsigned int 的建议(江南 Style 版) [英] Advice on unsigned int (Gangnam Style edition)
问题描述
视频Gangnam Style"(我相信你已经听说过)在 youtube 上的观看次数刚刚超过 20 亿.事实上,谷歌表示他们从未期望视频大于 32 位整数......这暗示谷歌使用 int
而不是 unsigned
他们的观点计数器.我认为他们不得不稍微重新编写代码以适应更大的视图.
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-bit integer... which alludes to the fact that Google used int
instead of unsigned
for their view counter. I think they had to re-write their code a bit to accommodate larger views.
检查他们的风格指南:https://google-styleguide.googlecode.com/svn/trunk/cppguide.html#Integer_Types
...他们建议不要使用无符号整数类型",并给出一个很好的理由:unsigned
可能有问题.
...they advise "don't use an unsigned integer type," and give one good reason why: unsigned
could be buggy.
这是一个很好的理由,但可以防范.我的问题是:通常使用 unsigned int
是不好的编码习惯吗?
It's a good reason, but could be guarded against. My question is: is it bad coding practice in general to use unsigned int
?
推荐答案
Google 规则已被专业界广泛接受.问题是无符号整数类型有点坏,并且有用于数值时的意外和不自然的行为;他们不能很好地作为基数类型.例如,数组的索引可能永远不会是负面的,但写起来很有意义abs(i1 - i2)
找到两个索引之间的距离.这将不起作用,如果i1
和 i2
具有无符号类型.
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.
作为一般规则,Google 样式指南中的此特定规则或多或少符合语言设计者的意图.任何时候你看到除 int
以外的东西,你都可以假设一个特殊的原因.如果是因为范围的原因,它将是 long
或long long
,甚至int_least64_t
.使用无符号类型通常是您正在处理位的信号,而不是数字值变量,或者(至少在 unsigned char
的情况下)你是处理原始内存.
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.
关于使用 unsigned
的自我文档":这个不成立,因为几乎总是有很多值变量不能(或不应该)采取,包括许多积极的.C++没有子范围类型,并且 unsigned
的定义方式意味着它也不能真正用作一个.
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.
这篇关于关于 unsigned int 的建议(江南 Style 版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!