sizeof
is a C keyword. It returns the size in a type named size_t
. However, size_t
is not a keyword, but is defined primarily in stddef.h
and probably other C standard header files too.
Consider a scenario where you want to create a C program which does not include any C standard headers or libraries. (Like for example, if you are creating an OS kernel.) Now, in such code, sizeof
can be used (it is a C keyword, so it is a part of the language), but the type that it returns (size_t
) is not available!
Does not this signify some kind of a problem in the C standard specification? Can you clarify this?
size_t is a base unsigned integer memsize-type defined in the standard library of C/C++ languages. This type is described in the header file stddef. h for C and in the file cstddef for C++. Types defined by the header file stddef.
size_t is unsigned because negative sizes make no sense.
size_t is an identifier and is not part of the language.
size_t is the unsigned integer type of the result of sizeof , _Alignof (since C11) and offsetof, depending on the data model.
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.
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.
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