what if assignning -1 to an unsigned type

deal all:
i saw this static const size_t npos = -1; in the string reference,yet because size_t is an unsigned integral type,i do know if it is safe to do so,or does it make any sense ?

thanks in advance!
On 2's complement systems, -1 is represented as "all bits set".

So the above line is basically the same thing as npos = 0xFFFFFFFF;.
Not the best way to set all bits, actually. ~0 or UINT_MAX are preferable. I don't know why they didn't use that.
@helios

is not ~0=0xffffffff ? i do not see there is any difference between the two ?
-1 and ~0 both have the same end result in this case.

helios was saying that ~0 is better than -1 because it doesn't depend on the underlying system being 2's compliment.
is not ~0=0xffffffff ? i do not see there is any difference between the two ?
That's more or less what I was saying, but not quite.
I was saying that (unsigned)-1 is not the best way to set all bits, because on some architectures, (unsigned)-1 translates to ~1. ~0 sets all bits regardless of the architecture, but it's not the same as 0xFFFFFFFF. For example, if sizeof(int)==8, the upper 32 bits are still cleared with 0xFFFFFFFF (0x00000000FFFFFFFF).
Last edited on
thanks, i see what you mean.
Topic archived. No new replies allowed.