I see variables defined with this type but I don\'t know where it comes from, nor what is its purpose. Why not use int or unsigned int? (What about other \"similar\" types?
This way you always know what the size is, because a specific type is dedicated to sizes. The very own question shows that it can be an issue: is it an int
or an unsigned int
? Also, what is the magnitude (short
, int
, long
, etc.)?
Because there is a specific type assigned, you don't have to worry about the length or the signed-ness.
The actual definition can be found in the C++ Reference Library, which says:
Type:
size_t
(Unsigned integral type)Header:
<cstring>
size_t
corresponds to the integral data type returned by the language operatorsizeof
and is defined in the<cstring>
header file (among others) as an unsigned integral type.In
<cstring>
, it is used as the type of the parameternum
in the functionsmemchr
,memcmp
,memcpy
,memmove
,memset
,strncat
,strncmp
,strncpy
andstrxfrm
, which in all cases it is used to specify the maximum number of bytes or characters the function has to affect.It is also used as the return type for
strcspn
,strlen
,strspn
andstrxfrm
to return sizes and lengths.
In minimalistic programs where a size_t
definition was not loaded "by chance" in some include but I still need it in some context (for example to access std::vector<double>
), then I use that context to extract the correct type. For example typedef std::vector<double>::size_type size_t
.
(Surround with namespace {...}
if necessary to make the scope limited.)
As for "Why not use int or unsigned int?", simply because it's semantically more meaningful not to. There's the practical reason that it can be, say, typedef
d as an int
and then upgraded to a long
later, without anyone having to change their code, of course, but more fundamentally than that a type is supposed to be meaningful. To vastly simplify, a variable of type size_t
is suitable for, and used for, containing the sizes of things, just like time_t
is suitable for containing time values. How these are actually implemented should quite properly be the implementation's job. Compared to just calling everything int
, using meaningful typenames like this helps clarify the meaning and intent of your program, just like any rich set of types does.