Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 801
Philip Avatar asked May 14 '11 19:05

Philip


People also ask

Should I use Size_t instead of int?

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.

Is Size_t bigger than int?

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.

What is the purpose of Size_t?

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.

Should I always use Size_t?

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.


1 Answers

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).

like image 54
Michael Burr Avatar answered Oct 20 '22 17:10

Michael Burr