javanetbeans's blog

By javanetbeans, 12 years ago, In English

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?

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
12 years ago, # |
Rev. 3   Vote: I like it +7 Vote: I do not like it

. . .

  • »
    »
    12 years ago, # ^ |
      Vote: I like it +1 Vote: I do not like it

    The size() method returns an unsigned int so -4 becomes 4294967292.

»
12 years ago, # |
  Vote: I like it +9 Vote: I do not like it

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 type basic_string<> is defined as a basic template class for all string types:

namespace std 
{
	template<class charT,
			 class traits = char_traits<charT>,
			 class Allocator = allocator<charT> >
	class basic_string;
}

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:

namespace std 
{
	template <class T>
	class allocator 
	{
		public:
		//type definitions
		typedef size_t    size_type;
		
		/*	Other type definitions and functions.	*/
		...
	}
}

In the C++ standard library, the string class is the predefined specialization of basic_string<> template for characters of type char:

namespace std 
{
	typedef basic_string<char> string;
}

As this specialization use the default allocator, then the type string::size_type is size_t, which is unsigned.

»
12 years ago, # |
  Vote: I like it 0 Vote: I do not like it

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