relaxxx
relaxxx

Reputation: 7824

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...

Upvotes: 7

Views: 1941

Answers (4)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

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.

Upvotes: 6

salezica
salezica

Reputation: 76929

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.

Upvotes: 4

James
James

Reputation: 1691

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.

Upvotes: 2

nyxdis
nyxdis

Reputation: 417

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).

Upvotes: -2

Related Questions