简体   繁体   English

将签名转换为未签名

[英]casting signed to unsigned

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...我读过它跨平台是不安全的,但我在很多“专业”代码中看到了这一点......

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.您阅读的任何内容的作者都可能认为(unsigned)-1下溢,并可能在位表示不会给您UINT_MAX麻烦的系统上造成混乱。

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() .无论涉及什么位表示, (unsigned)-1都是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.你会得到那个大的,最大值。如果这很好,我猜你对 go 很好。

If you wanted to get UINT_MAX, I'm pretty sure that's actually the best way of doing it.如果您想获得 UINT_MAX,我很确定这实际上是最好的方法。 Casting -1 to unsigned is guaranteed to yield UINT_MAX.将 -1 转换为unsigned保证会产生 UINT_MAX。 It's explained in the comments.评论中对此进行了解释。

It is unsafe because what an enum is is not clearly defined.这是不安全的,因为没有明确定义枚举。

See Are C++ enums signed or unsigned?请参阅C++ 枚举是签名还是未签名? 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.归根结底,您所写的内容看起来最终会成为 (int)(unsigned int)(int) 翻译,所以我不确定您要完成什么。

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 (ie INT_MAX).不太确定这是否是实现定义的,但是将 -1(显然是有符号的)转换为无符号的 integer 会导致下溢,这通常会导致非常大的值(即 INT_MAX)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM