简体   繁体   中英

Converting std::string::length to int

string::length has the return type of size_t, but it seems to able to be put into an int without any casting or anything. Why can I assign a size_t to an int in this case?

int main() {
     string line;
     getline(cin, line);
     cout << line << endl;
     int i = line.size();
     int j = line.length();
     cout << i << " " << j << endl;
}

The size_t values are being narrowed. In c++11, you could make this fail with an error by doing:

#include <string>

int main() {
    std::string line;
    int i{line.size()};
    int j{line.length()};
}

The errors produced look like:

gh.cc:5:11: error: non-constant-expression cannot be narrowed from type 'size_type' (aka 'unsigned long') to 'int' in initializer list [-Wc++11-narrowing]
    int i{line.size()};
          ^~~~~~~~~~~
gh.cc:5:11: note: override this message by inserting an explicit cast
    int i{line.size()};
          ^~~~~~~~~~~
          static_cast<int>( )
gh.cc:6:11: error: non-constant-expression cannot be narrowed from type 'size_type' (aka 'unsigned long') to 'int' in initializer list [-Wc++11-narrowing]
    int j{line.length()};
          ^~~~~~~~~~~~~
gh.cc:6:11: note: override this message by inserting an explicit cast
    int j{line.length()};
          ^~~~~~~~~~~~~
          static_cast<int>( )

size_t is a 32 bit integer. Go to your compiler directory and open the stdio.h file.

There is a declaration, something like this:

typedef unsigned int size_t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM