G G said:
typedef unsigned int size_t
.............
size_t
when to declare something size_t? when the variable is associated
with memory usage?
at any other time should the variable be declared an unsigned int?
it's not a question of style, right?
The type size_t is the type of the result of the sizeof operator,
measuring a size in char-sized bytes of (the type of) its
operand. In C11, the type size_t was chosen also for the result
of the _Alignof operator, which is fairly natural even though
what _Alignof is measuring is not exactly a size (though it is in
units of char-sized bytes). On some platforms size_t is the same
as unsigned int, but that's not true of all platforms. In most
cases size_t is the same as either unsigned int or unsigned long,
but the Standard doesn't require that.
The only absolute rule for size_t is the one pointed out by James
Kuyper, namely, when dealing with something that expects a
pointer to size_t (eg, as a parameter or a return value), only
that type [*] will work. Similarly this is true for pointers to
pointers to size_t, etc. [*] The reason for the asterisk is to
explain the variations related to void * and various qualified
versions, eg, (const size_t *), but these are the same as for all
other pointer types.
Beyond that, any decision about using size_t is stylistic. For
example, if size_t can hold the size of any object, then because
an element of an array is always at least one byte a size_t value
can hold the extent of the array, ie, the number of elements it
has. This naturally suggests that size_t might be a good choice
for variables meant to hold array extents, and this choice is
used by many library functions. Similarly a size_t value might
be used to keep a count of how many elements in an array satisfy
a certain property, or a position within an array of an element
that meets some criteria. All of these are plausible reasons for
choosing size_t for certain uses, but again they are not
absolute, not mandatory.
An interesting question is whether to use size_t for variables
used for indexing, eg, in for() loops. There are different
schools of thought about whether such variables should be signed
or unsigned. Obviously, if we want our index variables to be
signed, size_t is not a workable choice.
Personally, I avoid using size_t in most cases where there is a
choice. My preference is to reserve size_t for only those
places where what is being held is a size in bytes of some
area of memory; using it for other purposes, eg, array extents
or index variables, IMO makes code harder to understand rather
than easier, and therefore should be avoided for that reason.