sizeof
is a C keyword. It returns the size in a type named size_t
. However, size_t
is not a keyword, but is
sizeof
is a keyword because, despite it's name and usage, it is an operator like +
or =
or <
rather than a function like printf()
or atoi()
or fgets()
. A lot of people forget (or just don't know) that sizeof
is actually an operator, and is always resolved at compile-time rather than at runtime.
The C language doesn't need size_t
to be a usable, consistent language. That's just part of the standard library. The C language needs all operators. If, instead of +
, C used the keyword plus
to add numbers, you would make it an operator.
Besides, I do semi-implicit recasting of size_t
s to unsigned int
s (and regular int
s, but Kernighan and Ritchie will someday smite me for this) all the time. You can assign the return type of a sizeof
to an int if you like, but in my work I'm usually just passing it straight on to a malloc()
or something.
It does not literally return a value of type size_t since size_t is not a concrete type in itself, but rather a typedef to an unspecified built-in type. Typedef identifiers (such as size_t) are completely equivalent to their respective underlying types (and are converted thereto at compile time). If size_t is defined as an unsigned int on your platform, then sizeof returns an unsigned int when it is compiled on your system. size_t is just a handy way of maintaining portability and only needs to be included in stddef.h if you are using it explicitly by name.
I think that the main reasons that size_t
is not a keyword are:
For example, in discussing the next major revision of the C++ standard, Stroustrup had this to say:
The C++0x improvements should be done in such a way that the resulting language is easier to learn and use. Among the rules of thumb for the committee are:
...
- Prefer standard library facilities to language extensions
...
From MSDN:
When the sizeof operator is applied to an object of type char, it yields 1
Even if you don't have stddef.h available/included and don't know about size_t, using sizeof you can get the size of objects relative to char.