将签名转换为未签名

发布于 2024-11-10 17:13:46 字数 152 浏览 4 评论 0原文

这样做正确吗?

typedef unsigned int Index;

enum
{
  InvalidIndex = (Index) -1 
};

我读过它跨平台不安全,但我在很多“专业”代码中看到了这一点......

is it correct to do this?

typedef unsigned int Index;

enum
{
  InvalidIndex = (Index) -1 
};

I have read that it is unsafe across platforms, but I have seen this in so many "professional" codes...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

九厘米的零° 2024-11-17 17:13:46

你读到的内容可能是出于恐惧、不确定性和怀疑。无论您读到什么内容,作者都可能认为 (unsigned)-1 下溢,并且可能会在系统上造成混乱,因为系统中的位表示恰好无法为您提供 UINT_MAX麻烦。

然而,作者错了,因为标准保证无符号值在到达范围边缘时回绕。无论涉及什么位表示,(unsigned)-1 std::numeric_limits::max()。时期。

不过,我不确定它在这里有什么好处。你将获得那么大的最大值。如果没问题,我想你就可以开始了。

What you read was probably out of Fear, Uncertainty and Doubt. The author of whatever you read probably thought that (unsigned)-1 was underflowing and potentially causing chaos on systems where the bit representation doesn't happen to give you UINT_MAX for your trouble.

However, the author is wrong, because the standard guarantees that unsigned values wrap-around when they reach the edge of their range. No matter what bit representations are involved, (unsigned)-1 is std::numeric_limits<unsigned>::max(). Period.

I'm not sure what the benefit of it is here, though. You're going to get that large, maximum value.. If that is fine, I guess you're good to go.

魂ガ小子 2024-11-17 17:13:46

如果您想获得 UINT_MAX,我很确定这实际上是最好的方法。将 -1 转换为 unsigned 保证产生 UINT_MAX。评论里已经解释了。

If you wanted to get UINT_MAX, I'm pretty sure that's actually the best way of doing it. Casting -1 to unsigned is guaranteed to yield UINT_MAX. It's explained in the comments.

深者入戏 2024-11-17 17:13:46

它是不安全的,因为枚举是什么没有明确定义。

有关详细信息,请参阅C++ 枚举是有符号的还是无符号的?

最终,您所写的内容看起来最终会被翻译成 (int)(unsigned int)(int) ,所以我不确定您想要完成什么。

It is unsafe because what an enum is is not clearly defined.

See Are C++ enums signed or unsigned? for more information on that.

At the end of the day what you have written looks like it would end up being (int)(unsigned int)(int) in translation so I am not sure what you are trying to accomplish.

小苏打饼 2024-11-17 17:13:46

不太确定这是否是实现定义的,但将 -1 (显然是有符号的)转换为无符号整数会导致下溢,这通常会导致极大的值(即 INT_MAX)。

Not quite sure if this is implementation defined, but casting -1 (which is obviously signed) to an unsigned integer causes an underflow, which usually leads to extremely large values (i.e. INT_MAX).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文