Search code examples
c++stringstring-length

string::length returns false value?


string str = "abcdef";
cout << str.length() << endl; //6
cout << str.length() - 7 << endl; //4294967295

I don't understand why str.length() - 7 returned 4294967295 instead of -1.

Could you help me to explain this?


Solution

  • The return type of str.length() is size_t:

    size_t length() const noexcept;

    you can think about it as an unsigned int for this case.

    The unsigned integer underflows when it gets to a negative value, wraps around and goes to other extreme, causing you, to see in your system 4294967295.

    4294967295 (2^32 - 1) corresponds to the maximum value of a 32-bit unsigned type - which is consistent with a fair few 32-bit implementations. Moreover size_t can be, but is not required to be, a 32-bit type.