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

后端 未结 7 1436
-上瘾入骨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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-20 16:35

    I was wondering about this too. Turns out that the struct NOTHING_LIKE_xyz * z is forward declaring struct NOTHING_LIKE_xyz. As a convoluted example,

    typedef struct {
        struct foo * bar;
        int j;
    } foo;
    
    struct foo {
        int i;
    };
    
    void foobar(foo * f)
    {
        f->bar->i;
        f->bar->j;
    }
    

    Here f->bar refers to the type struct foo, not typedef struct { ... } foo. The first line will compile fine, but the second will give an error. Not much use for a linked list implementation then.

提交回复
热议问题