Why is (18446744073709551615 == -1) true?

后端 未结 4 1151
囚心锁ツ
囚心锁ツ 2020-12-17 10:16

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)
         


        
4条回答
  •  醉梦人生
    2020-12-17 10:40

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

提交回复
热议问题