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

后端 未结 7 1441
-上瘾入骨i
-上瘾入骨i 2020-12-20 15:52

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;
} x         


        
7条回答
  •  萌比男神i
    2020-12-20 16:14

    You do have to name it. In this:

    typedef struct {
        struct xyz *z;
    } xyz;
    

    will not be able to point to itself as z refers to some complete other type, not to the unnamed struct you just defined. Try this:

    int main()
    {
        xyz me1;
        xyz me2;
        me1.z = &me2;   // this will not compile
    }
    

    You'll get an error about incompatible types.

提交回复
热议问题