Does union support flexible array members?

前端 未结 3 1412
闹比i
闹比i 2021-01-06 10:36

I have declared a flexible array member in union, like this:

#include  

union ut
{
    int i;
    int a[]; // flexible array member
};

int m         


        
相关标签:
3条回答
  • 2021-01-06 10:44

    No, unions do not support flexible array members, only structs. C11 6.7.2.1 §18

    As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member.

    In addition, zero-length arrays is not valid C, that's a gcc non-standard extension. The reason why you get this to work is because your compiler, gcc, is configured to compile code for the "non-standard GNU language". If you would rather have it compile code for the C programming language, you need to add compiler options -std=c11 -pedantic-errors.

    0 讨论(0)
  • 2021-01-06 10:49

    int a[] is the C standard notation (since C99).

    int a[0] is GNU C syntax, which predates C99. Other compilers might also support it, I don't know.

    Your compiler seems to default to C90 standard with GNU extensions, which is why latter compiles, but first one does.

    Furthermore, as stated in Lundin's answer, standard C does not support flexible array members in union at all.


    Try adding -std=c99 or -std=c11 to your compiler options (gcc docs here).

    Also -pedantic or -pedantic-errors is probably a good idea too, it'll enforce more strict standard compliance.

    And, obligatory aside, -Wall -Werror won't hurt either...

    0 讨论(0)
  • 2021-01-06 10:59

    I'm not sure what the standard would say about this, but G++' unions seems to accept flexible arrays just fine. If you wrap them in an anonymous struct first, like so:

    union {
       unsigned long int  ul;
       char  fixed[4][2];
       struct {
          char  flexible[][2];
       };
    };
    
    0 讨论(0)
提交回复
热议问题