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 int
s 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?
When writing C code you should always use size_t whenever dealing with memory ranges. The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic.
If we consider the standard, both are integers of size 16 bits. On a typical 64-bit system, the size_t will be 64-bit, but unsigned int will be 32 bit. So we cannot use them interchangeably. One standard recommendation is that the size_t be at most as big as an unsigned long.
size_t type is a base unsigned integer type of C/C++ language. It is the type of the result returned by sizeof operator. The type's size is chosen so that it can store the maximum size of a theoretically possible array of any type. On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits.
size_t is an unsigned integer that is capable of holding the size of the largest object you can allocate. It is useful for indexing because this means it can index into the largest array you can allocate. This does not mean it is required or even necessarily recommended for indexing.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With