Bahadır Bahadır - 19 days ago 6
C++ Question

Why is (18446744073709551615 == -1) true?

When I was working on

string::npos
I noticed something and I couldn't find any explanation for it on the web.

(string::npos == ULONG_MAX)


and

(string::npos == -1)


are true.

So I tried this:

(18446744073709551615 == -1)


which is also true.

How can it be possible? Is it because of binary conversation?

Answer

string::npos is defined as constexpr static std::string::size_type string::npos = -1; (or if it's defined inside the class definition that would be constexpr static size_type npos = -1; but that's really irrelevant).

The wraparound of negative numbers converted to unsigned types (std::string::size_type is basically std::size_t, which is unsigned) is perfectly well-defined by the Standard. -1 wraps to the largest representable value of the unsigned type, which in your case is 18446744073709551615. Note that the exact value is implementation-defined because the size of std::size_t is implementation-defined (but capable of holding the size of the largest possible array on the system in question).

Comments