Struct hack equivalent in C++

前端 未结 6 2052
礼貌的吻别
礼貌的吻别 2020-12-25 12:47

The struct hack where you have an array of length 0 as the last member of a struct from C90 and C99 is well known, and with the introduction of flexible array members in C99

6条回答
  •  我在风中等你
    2020-12-25 13:21

    There is at least one advantage for flexible array members over zero length arrays when the compiler is clang.

    struct Strukt1 {
        int fam[];
        int size;
    };
    
    struct Strukt2 {
        int fam[0];
        int size;
    };
    

    Here clang will error if it sees Strukt1 but won't error if it instead sees Strukt2. gcc and icc accept either without errors and msvc errors in either case. gcc does error if the code is compiled as C.

    The same applies for this similar but less obvious example:

    struct Strukt3 {
        int size;
        int fam[];
    };
    
    strukt Strukt4 {
        Strukt3 s3;
        int i;
    };
    

提交回复
热议问题