What is size_t and why should I use it?

CMP
3 min readJun 5, 2023

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 to unsigned int . For 64-bit systems, it may be equivalent to unsigned long or unsigned 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 consider size_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 the size() member function of std::vector . If you use any of these containers in your code (and you probably do), then using size_t is a good idea to maintain consistency and…

--

--

CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.