ccompiler-errorsflexible-array-member

Why single (flexible array) member struct declaration is only supported by [0] and not []?


Basically:

struct foo_1
{
    int flexible_guy[0]; // this works
};

struct foo_2
{
    int flexible_guy[]; // this doesn't (error: flexible array member in a struct with no named members)
};

Is this the intended logic for some reason, an easter egg workaround for something not supported, or a compiler bug?

I'm using GCC 7.5.0 on Ubuntu 18.04, but I get the same result on a web compiler that uses GCC 9.4.0 (https://onlinegdb.com/_15wOU3UF).


Solution

  • gcc supports zero length arrays as an extension, which is why the first one is allowed.

    https://gcc.gnu.org/onlinedocs/gcc/Zero-Length.htm

    The second case doesn't fall under this extension, so it falls back on what the C standard states, which doesn't allow an array with unspecified size in a struct as the only member.

    From section 6.7.2.1p3 of the C standard regarding Struct and Union Specifiers under the Constraints heading:

    A structure or union shall not contain a member with incomplete or function type (hence, a structure shall not contain an instance of itself, but may contain a pointer to an instance of itself), except that the last member of a structure with more than one named member may have incomplete array type; such a structure (and any union containing, possibly recursively, a member that is such a structure) shall not be a member of a structure or an element of an array.

    The above gcc page on zero length arrays also mentions this:

    Flexible array members may only appear as the last member of a struct that is otherwise non-empty