Converting std::string::length to int

Matt

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;
}
Bill Lynch

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related