Is there a difference between -1 and ~0?
c, c++
Solution
The C++ standard guarantees that `size_t` is an unsigned type, that unsigned types obey the usual modular arithmetic rules (where the modulus is two to the number of bits in the value representation of the type, cf. 3.9/4), and thus `-1` converted to `size_t` must be the largest value which that type can represent.
The value `0` is an `int`, and `~0` has all the bits in the `int` representation of zero flipped. The value of that result depends on the representation of `int` on your platform. That value (which may be a trap representation, thanks @Matt McNabb) is then converted to `size_t` (which is done following the rules of modular arithmetic).
In conclusion, whether the resulting values compare equal is implementation defined. (For example, if `int` is represented in two's complement, then the value of `~0` is `-1`, so the two are the same.)
Problem
When comparing a unsigned value, as in this test: ``` if (pos == (size_t)-1) ``` Is this comparison technically different from something like: ``` if (pos == (size_t)~0) ``` I am not used to the second variant. That's why I am asking the question. The answer may be rather straighforward if it's yes.