Question

Is for example

size_t x = -1u;

if (x == -1u)
    ...

valid?

If this is valid it would prevent a warning. of course on a 32 bit system x should be 0xffffffff and on a 64 bit system it should be 0xffffffffffffffff.

-Jochen

Was it helpful?

Solution

1u has the type unsigned int. This is then negated using the unary - operator. The behavior is as follows:

The negative of an unsigned quantity is computed by subtracting its value from 2n, where n is the number of bits in the promoted operand (C++11 5.3.1/8).

-1u is thus guaranteed to give you the largest value representable by unsigned int.

To get the largest value representable by an arbitrary unsigned type, you can cast -1 to that type. For example, for std::size_t, consider static_cast<std::size_t>(-1).

OTHER TIPS

I've always used ~0U for the purpose of "unsigned, all bits on".

Compiler implementation dependant behavior is annoying. You should be able to do this, though:

size_t x = 0;
x--;

if ((x+1) == 0)

While this is technically valid code, you are depending on implementation dependent behavior: overflow handling of converting a negative number to unsigned. However, if you need to meaningful compare a size_t with -1 because the API calls you are using require it, the system is already screwed up but your code is likely to work because they would have had to do the same thing on the other side of the API.

This is likely what you want:

size_t x = -1ull;

if (x == -((size_t)-1ull))
    ...

x will be set to the largest integer possible, which may not be all bits set. Use ~0 for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top