I'm currently in the process of converting some uses of unsigned int
to size_t
in my a code base that I have been developing over the years. I understand the difference between the two and that for example unsigned int
could be 32-bit while pointers and size_t
could be 64-bit. My question is more about where I should use either one and what kind of convention people use for picking between the two.
It's quite clear that memory allocation should take size_t
instead of unsigned int
as an argument, or that container classes should use size_t
for size and indexing like in STL. These are the common cases referred when reading about the benefits of size_t
vs unsigned int
. However, while working on the code base conversion I stumbled upon quite a few cases in gray areas where I'm not sure which one to use. For example if 4x4 matrix row/column index should be size_t
for consistency regardless the index being in range [0, 3], or if screen/texture resolution should use size_t
despite of being in range of few thousand, or in general if the reasonable number of objects is expected to be in the range of tens I should still use size_t
for consistency.
What kind of coding conventions you use for picking between unsigned int
and size_t
? Should everything that's representing size (in bytes or objects), or index be always size_t
regardless of the reasonably expected range? Is there some widely accepted size_t
convention used in well-established libraries that I could follow?
I think it's simple, although I welcome the slings and arrows.
size_t
should be used if it describes something that has a size. (A count. A number of things)