size_t
is an important data type that every C++ programmer should know about, especially if you need highly portable, maintainable, and efficient code.
What is it?
In C/C++, size_t
is an unsigned integer type that is commonly used to store the size or length of an object or container. According to the C++ reference, size_t
can hold “the maximum size of a theoretically possible object of any type”. In other words, no matter how large your object, array, container, etc. is, as long as it can be constructed, size_t
can hold its size.
When should I use it and why?
- You need portability:
size_t
is guaranteed to be at least 16-bits wide, but the exact size is dependent on the compiler used and the architecture of the system. For 32-bit systems, it’s likely an alias tounsigned int
. For 64-bit systems, it may be equivalent tounsigned long
orunsigned long long
. Therefore, if your program may run on devices of various architectures (you should probably assume so) and/or if your program may be built with more than one known compiler, then you should considersize_t
whenever possible. - You use the C++ Standard Library: Standard library containers often use
size_t
as the return type and/or parameter types for their member functions, such as thesize()
member function ofstd::vector
. If you use any of these containers in your code (and you probably do), then usingsize_t
is a good idea to maintain consistency and…