Where do I find the definition of size_t?

前端 未结 9 2130
醉酒成梦
醉酒成梦 2020-11-28 04:37

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?

相关标签:
9条回答
  • 2020-11-28 05:02

    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 operator sizeof 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 parameter num in the functions memchr, memcmp, memcpy, memmove, memset, strncat, strncmp, strncpy and strxfrm, 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 and strxfrm to return sizes and lengths.

    0 讨论(0)
  • 2020-11-28 05:03

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

    0 讨论(0)
  • 2020-11-28 05:08

    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, typedefd 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.

    0 讨论(0)
提交回复
热议问题