How is it legal to reference an undefined type inside a structure?

Posted by paxdiablo on Stack Overflow See other posts from Stack Overflow or by paxdiablo
Published on 2010-05-24T06:40:04Z Indexed on 2010/05/24 6:51 UTC
Read the original article Hit count: 247

Filed under:
|
|

As part of answering another question, I came across a piece of code like this, which gcc compiles without complaint.

typedef struct {
    struct xyz *z;
} xyz;
int main (void) {
    return 0;
}

This is the means I've always used to construct types that point to themselves (e.g., linked lists) but I've always thought you had to name the struct so you could use self-reference. In other words, you couldn't use xyz *z within the structure because the typedef is not yet complete at that point.

But this particular sample does not name the structure and it still compiles. I thought originally there was some black magic going on in the compiler that automatically translated the above code because the structure and typedef names were the same.

But this little beauty works as well:

typedef struct {
    struct NOTHING_LIKE_xyz *z;
} xyz;

What am I missing here? This seems a clear violation since there is no struct NOTHING_LIKE_xyz type defined anywhere.

When I change it from a pointer to an actual type, I get the expected error:

typedef struct {
    struct NOTHING_LIKE_xyz z;
} xyz;

qqq.c:2: error: field `z' has incomplete type

Also, when I remove the struct, I get an error (parse error before "NOTHING ...).

Is this allowed in ISO C?

© Stack Overflow or respective owner

Related posts about c

    Related posts about struct