Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: Why isn't size_t a C keyword?

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?

like image 933
Ashwin Nanjappa Avatar asked Apr 11 '09 08:04

Ashwin Nanjappa


People also ask

Is Size_t defined in C?

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.

Why is Size_t unsigned?

size_t is unsigned because negative sizes make no sense.

Is Size_t part of the STD?

size_t is an identifier and is not part of the language.

Is Size_t unsigned in C?

size_t is the unsigned integer type of the result of sizeof , _Alignof (since C11) and offsetof, depending on the data model.


2 Answers

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.

like image 138
Simon Broadhead Avatar answered Oct 24 '22 02:10

Simon Broadhead


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_ts to unsigned ints (and regular ints, 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.

like image 39
Chris Lutz Avatar answered Oct 24 '22 01:10

Chris Lutz