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?
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?
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.
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.