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
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)
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With