rulururu

post string::size_type and unsigned integer

March 11th, 2008

Filed under: C++ — Kai @ 7:26 pm

The C++ std::string class provides string::size_type as an integer datatype large enough to represent any possible string size.

The ‘find’ member function returns the location of the first occurrence of a substring or character in a string. This return value is an integer (whose type is string::size_type). If the substring or character is not found, it needs some value to return that signals this fact.

std::string::size_type std::string::find
                          (char c, std::string::size_type pos ) const;

The maximum value of an int is 2,147,483,647.

Meaning that if a line won’t hold more than 2,147,483,647 characters - which in normal cases never do - then you don’t have to bother declaring string::size_type, you can just declare an integer, which is more simple.

You’d also keep in mind that in theory, you don’t have any knowledge about string::size_type, it could be a 16-bit integer, a 32-bit integer or a 64-bit integer. The only thing a size_type is guaranteed to be is an unsigned integral type.

Even declaring an int for keeping the return value of a function that returns an string::size_type you get a warning because correct thing to do is to always use the string::size_type. That is guaranteed to always work when using C++ STL.

By the way I found this in GCC source code:

#undef SIZE_TYPE
#define SIZE_TYPE "unsigned int"

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

ruldrurd
Powered by WordPress, Content and Design by Kai Bellmann
Entries (RSS) and Comments (RSS)