0
int main () {
string s = "";
cout << s.size() << endl;
cout << s.size() - 5 << endl;
return 0;
}

The above code output is following:

0
18446744073709551611

Why the second result is not -5?

  • As described in the documentation: [std::string::size](https://en.cppreference.com/w/cpp/string/basic_string/size) returns [`std::size_t`](https://en.cppreference.com/w/cpp/types/size_t), which is "unsigned integer type". Unsigned integers don't have negative values. – Algirdas Preidžius Oct 05 '18 at 13:17
  • Related: https://stackoverflow.com/questions/5563000/implicit-type-conversion-rules-in-c-operators "Otherwise, if either operand is unsigned, the other shall be converted to unsigned. " – Yksisarvinen Oct 05 '18 at 13:17

2 Answers2

3

Because std::string::size() returns a value of type std::string::size_type which is an unsigned integer type (no, this is not guaranteed to be unsigned int, use std::size_t (<cstddef>)). To perform the subtraction both operand values undergo integral promotion by which both values are promoted to a common type - in this case std::string::size_type, then the subtraction is performed.

Integral Promotions

Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • So in this question, the `s.size() - 5`, `s.size()` is promoted to int type? Why it not 0, but a large number value. – sourcecode Oct 06 '18 at 02:12
1

std::string::size returns an unsigned integer type. Underflow of unsigned type is well-defined and causes the result to wrap around, starting at the maximum value that the type can represent.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416