Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is -1u valid c++?

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

like image 382
Jochen Avatar asked Dec 05 '11 20:12

Jochen


3 Answers

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

like image 134
James McNellis Avatar answered Oct 06 '22 23:10

James McNellis


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

like image 28
StilesCrisis Avatar answered Oct 06 '22 23:10

StilesCrisis


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

size_t x = 0;
x--;

if ((x+1) == 0)
like image 41
Adam Davis Avatar answered Oct 07 '22 01:10

Adam Davis