Can sizeof return 0 (zero)

后端 未结 10 1570
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 08:14

Is it possible for the sizeof operator to ever return 0 (zero) in C or C++? If it is possible, is it correct from a standards point of view?

10条回答
  •  一个人的身影
    2020-11-28 08:50

    In C++ an empty class or struct has a sizeof at least 1 by definition. From the C++ standard, 9/3 "Classes": "Complete objects and member subobjects of class type shall have nonzero size."

    In C an empty struct is not permitted, except by extension (or a flaw in the compiler).

    This is a consequence of the grammar (which requires that there be something inside the braces) along with this sentence from 6.7.2.1/7 "Structure and union specifiers": "If the struct-declaration-list contains no named members, the behavior is undefined".

    If a zero-sized structure is permitted, then it's a language extension (or a flaw in the compiler). For example, in GCC the extension is documented in "Structures with No Members", which says:

    GCC permits a C structure to have no members:

     struct empty {
     };
    

    The structure will have size zero. In C++, empty structures are part of the language. G++ treats empty structures as if they had a single member of type char.

提交回复
热议问题