C: Why isn't size_t a C keyword?

前端 未结 10 1841
鱼传尺愫
鱼传尺愫 2020-12-28 14:18

sizeof is a C keyword. It returns the size in a type named size_t. However, size_t is not a keyword, but is

相关标签:
10条回答
  • 2020-12-28 15:04

    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.

    0 讨论(0)
  • 2020-12-28 15:05

    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.

    0 讨论(0)
  • 2020-12-28 15:05

    I think that the main reasons that size_t is not a keyword are:

    • there's no compelling reason for it to be. The designers of the C and C++ languages have always preferred to have language features be implemented in the library if possible and reasonable
    • adding keywords to a language can create problems for an existing body of legacy code. This is another reason they are generally resistant to adding new keywords.

    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

    ...

    0 讨论(0)
  • 2020-12-28 15:05

    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.

    0 讨论(0)
提交回复
热议问题