C – Why Use size_t Instead of int for Array Size

c++intsize-tstandards

The C standard guarantees that an int is able to store every possible array size. At least, that's what I understand from reading §6.5.2.1, subsection 1 (Array subscripting constraints):

One of the expressions shall have type ‘‘pointer to object type’’, the other expression shall
have integer type, and the result has type ‘‘type’’.

Since we shall use ints as array subscripts, why are we supposed to use size_t to determine the size of an array?

Why does strlen() return size_t when int would suffice?

Best Answer

The term "integer type" doesn't mean int - for example, char, and short are integer types.

Just because you can use an int to subscript an array doesn't necessarily mean that it can reach all possible array elements.

More specifically about size_t vs. int, one example would be platforms where int might be a 16-bit type and size_t might be a 32-bit type (or the more common 32-bit int vs 64 bit size_t difference on today's 64-bit platforms).