Alex Rivera | Logout

Why size_t when int would suffice for the size of an array?

Asked 2011-05-14T19:50:40.710
15

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?

Edit
Report

1 Answer

2

Firstly, what you quoted from the standard does not make any references to type int specifically. And no, int is not guaranteed to be sufficient to store the size of any object (including arrays) in C.

Secondly, C language does not really have "array subscriptions" specifically. The array subscription is implemented through pointer arithmetic. And the integral operand in pointer arithmetics has ptrdiff_t type. Not size_t, not int, but ptrdiff_t. It is a signed type, BTW, meaning that the value can be negative.

Thirdly, the purpose of size_t is to store the size of any object in the program (i.e. to store the result of sizeof). It is not immediately intended to be used as an array index. It just happens to work as an array index since it is guaranteed that it is always large enough to index any array. However, from an abstract point of view, "array" is a specific kind of "container" and there are other kinds of containers out there (lists-based ones, tree-based ones and so on). In generic case size_t is not sufficient to store the size of any container, which in generic case makes it a questionable choice for array indexing as well. (strlen, on the other hand, is a function that works with arrays specifically, which makes size_t appropriate there.)

answered 2011-05-14T20:00:34.220

Your Answer