枚举范围混乱
如何找到枚举的范围? 我有两个版本,当最低值为负数时,它们的表述不同。Stroustrup 说的是,
enum e3 { min = -10 , max = 1000000 }; // range -1048576:1048575
但是 C++ Primer Plus 第五版说
例如,如果最小的枚举数是 -6,则下一个 2 的幂[乘负号]是 -8,因此下限是 -7
我很困惑哪个是正确的?
How to find the range of enums ?
I have got two versions which state it differently when the lowest value is negative.Stroustrup says that for
enum e3 { min = -10 , max = 1000000 }; // range -1048576:1048575
but
C++ Primer Plus 5th edition says
for eg if the smallest enumerator is -6, the next power of two [times a minus sign] is -8, and thus the lower limit is -7
I am confused which is correct ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我相信两者都是正确的(不过,请参阅下面的 Primer 定义),具体取决于您想要的兼容性。正式的定义是
对于负数,问题是我们使用什么表示形式。它的脚注说
如果您假设符号大小或补码,则示例枚举的范围为
-1048575:1048575
。对于二进制补码,您会在负数范围内多得到一个。 Primer 的定义缺少最大枚举值,所以我不确定它是如何达到下限-7
的。如果您想与其他实现最大程度地兼容,我会选择-1048575:1048575
。I believe both are correct (see below for Primer's definition, though), depending on how compatible you want to are. The formal definition is
For negative numbers, the question is what representation we use. The footnote to it says
If you assume sign magnitude or one's complement then the example enumeration's range is
-1048575:1048575
. For two's complement you get one more in the negative range. Primer's definiton lacks the maximum enumerator value, so I'm not sure how it comes to lower limit-7
. If you want to be maximum compatible with other implementations, I would go with-1048575:1048575
.C++ 标准规定 (§[dcl.enum]/7):
例如,在第一种情况下,
在第二种情况下,
因此,C++ Primer 是不正确的,因为它忽略了上限的影响。
The C++ standard says (§[dcl.enum]/7):
For example, in the first case,
In the second case,
Therefore, C++ Primer is incorrect, since it ignores the effect of the upper bound.
它们是完全相同的陈述,只是使用不同的尺度。要存储数字 1000000,您需要 20 位,因此您的范围是 -1048576 到 +1048575。要存储 -6,您需要 3 位,因此这 3 位可以存储的范围是 -8 到 +7。
They are exactly same statements, just using different scales. To store number 1000000 you need 20 bits, so your range is -1048576 to +1048575. To store -6 you need 3 bits, so the range you can store in those 3 bits is -8 to +7.