Search code examples
c++stringstring-lengthunsigned-integer

what type of data does string.length() return in c++?


I am a beginner in C++. Today, I was trying to solve problem 139 on Leetcode, here is the pseudo-code:

for (string& word: wordDict) {
    int i=0;
    int word_len = word.length();
    cout << i - word.length() << endl;
    cout << i - word_len << endl;
}

And here is the result:

18446744073709551611
-5
18446744073709551613
-3

Why does the integer seem out of range if I don't declare the type of word.length() in front?


Solution

  • The type of the member function length is an unsigned integer type named like size_type.

    As the type is unsigned then the expression

    i - word.length()
    

    also has an unsigned value because the rank of the type size_type (that usually corresponds to the type size_t) is not less than the rank of the type int.

    You could write for example

    i - ( int )word.length()
    

    to use signed arithmetic.