What is the size of an empty struct in C?

前端 未结 4 1960
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 06:07

According to me, it is zero but there seems to be bit confusion here

I have tested it with gcc compiler and it gives me zero as output. I know that in C++, size of an

4条回答
  •  臣服心动
    2020-11-30 06:13

    A struct cannot be empty in C because the syntax forbids it. Furthermore, there is a semantic constraint that makes behavior undefined if a struct has no named member:

    struct-or-union-specifier:
      struct-or-union identifieropt { struct-declaration-list }
      struct-or-union identifier
    
    struct-or-union:
      struct
      union
    
    struct-declaration-list:
      struct-declaration
      struct-declaration-list struct-declaration
    
    struct-declaration:
      specifier-qualifier-list struct-declarator-list ;
    
    /* type-specifier or qualifier required here! */
    specifier-qualifier-list:
      type-specifier specifier-qualifier-listopt
      type-qualifier specifier-qualifier-listopt
    
    struct-declarator-list:
      struct-declarator
      struct-declarator-list , struct-declarator
    
    struct-declarator:
      declarator
      declaratoropt : constant-expression
    

    If you write

    struct identifier { };
    

    It will give you a diagnostic message, because you violate syntactic rules. If you write

    struct identifier { int : 0; };
    

    Then you have a non-empty struct with no named members, thus making behavior undefined, and not requiring a diagnostic:

    If the struct-declaration-list contains no named members, the behavior is undefined.

    Notice that the following is disallowed because a flexible array member cannot be the first member:

    struct identifier { type ident[]; };
    

提交回复
热议问题