What is size_t in C?

Vijay picture Vijay · Mar 31, 2010 · Viewed 750.9k times · Source

I am getting confused with size_t in C. I know that it is returned by the sizeof operator. But what exactly is it? Is it a data type?

Let's say I have a for loop:

for(i = 0; i < some_size; i++)

Should I use int i; or size_t i;?

Answer

sblom picture sblom · Mar 31, 2010

From Wikipedia:

According to the 1999 ISO C standard (C99), size_t is an unsigned integer type of at least 16 bit (see sections 7.17 and 7.18.3).

size_tis an unsigned data type defined by several C/C++ standards, e.g. the C99 ISO/IEC 9899 standard, that is defined in stddef.h.1 It can be further imported by inclusion of stdlib.h as this file internally sub includes stddef.h.

This type is used to represent the size of an object. Library functions that take or return sizes expect them to be of type or have the return type of size_t. Further, the most frequently used compiler-based operator sizeof should evaluate to a constant value that is compatible with size_t.

As an implication, size_t is a type guaranteed to hold any array index.