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 "professiona开发者_如何学Pythonl" 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.
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.
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.
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.
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).
精彩评论