1

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;
}
Matt
  • 49
  • 1
  • 8

2 Answers2

3

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>( )
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
0

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;
Martin Wantke
  • 4,287
  • 33
  • 21