The size_t is chosen so that it can store the maximum size of a theoretically possible array or an object. In other words, the number of bits in size_t is equal to the number of bits required to store the maximum address in the machine's memory. On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits. It means a variable of size_t type can safely store a pointer. The exceptions are platforms with memory segmentation and pointers to class functions.
This type shifts responsibility about the possible different behavior of integer variables when changing the platform from the programmer shoulders to the implementation of the standard library. Therefore, using the size_t type is safer and more efficient than using ordinary unsigned integer types:
- This type allows you to write loops and counters without worrying about possible overflow when changing platforms. For example, when the number of required iterations exceeds UINT_MAX;
- Since the standard guarantees that size_t can store the size of the largest possible object in the system, this type is used to store object sizes;
- Because of this same size_t characteristic, it is also used to index arrays. Unlike the usual basic integer types, size_t guarantees that the index value cannot be greater than SIZE_MAX;
- Because size_t can usually safely store a pointer, it is used for address arithmetic. Although it is better to use another unsinged integer type uintptr_t for that purpose — its name reflects its capability.
- The compiler can build simpler and, therefore, faster code with no unnecessary conversions of 32-bit and 64-bit data.
In C, the size_t type is declared in the following header files: <stddef.h>, <stdlib.h>, <string.h>, <wchar.h>, <uchar.h>, <time.h>, and <stdio.h>. In C++, the size_t type declaration is located in the files: <cstddef>, <cstdlib>, <cstring>, <cwchar>, <cuchar>, <ctime>, and <cstdio>. The size_t type is placed in the global namespace and in std. Standard header files of the C language for backward compatibility can also be included in C++ programs.
In terminology of the PVS-Studio static analyzer, the size_t type refers to memsize types. The analyzer has a large number of special 64-bit diagnostic rules issued by the analyzer and related to recommendations on using memsize-types. If you are planning to start developing cross-platform projects or porting existing 32-bit projects to 64-bit systems, you may use PVS-Studio analyzer which can simplify this task greatly and allow you to avoid the long stage of searching for hidden errors.
To learn more about the errors you can avoid when using size_t type and also how this type allows improving and optimizing your programs, see the articles given in the references.