Does union support flexible array members?

Viewed 4409

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

#include  <stdio.h>

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

int main(void)
{
    union ut s;
    return 0;
}

and compiler gives an error :

source_file.c:8:9: error: flexible array member in union
     int a[];

But, Declared array zero size like this :

union ut
{
    int i;
    int a[0]; // Zero length array
};

And it's working fine.

Why does zero length array work fine union?

3 Answers

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];
   };
};
Related