Today I was trying this code in C++:
string s1 = "a";
string s2 = "bcdef";
cout << s1.size() << " " << s2.size() << endl; //output 1 5
cout << (s1.size() — s2.size()) << endl; // output 4294967292
if I do,
cout << (int)(s1.size() — s2.size()) << endl; // then output -4.
Is this due to reason that s1.size() returns unsigned int.
Can you please exactly tell me, what's the funda for this?
. . .
The size() method returns an unsigned int so -4 becomes 4294967292.
The return type of size, length, and all find functions in string class is string::size_type, an unsigned integral type that is defined inside the string class.
Inside
<string>
header, the typebasic_string<>
is defined as a basic template class for all string types:It is parameterized by the character type, the traits of the character type, and the memory model.
The third optional argument defines the memory model that is used by the string class. As usual, the default value is the default memory model allocator.
The default allocator is declared as follows:
In the C++ standard library, the string class is the predefined specialization of
basic_string<>
template for characters of type char:As this specialization use the default allocator, then the type string::size_type is size_t, which is unsigned.
Type size_t should store size of any array-like entity in memory, so it's unsigned and has the same bit count as the RAM address. For difference of sizes there is relevant type — ptrdiff_t. In STL usually ::size_type == size_t and ::difference_type == ptrdiff_t. Holy Standard 2003 5.7.6