开发者

How can `struct conn_queue` be used before defined?

开发者 https://www.devze.com 2023-03-08 09:47 出处:网络
This code works: typedef struct conn_queue CQ; struct conn_queue { CQ_ITEM *hea开发者_开发知识库d;

This code works:

typedef struct conn_queue CQ;
struct conn_queue {
    CQ_ITEM *hea开发者_开发知识库d;
    CQ_ITEM *tail;
    pthread_mutex_t lock;
    pthread_cond_t  cond;
};

I think it should be like this:

struct conn_queue {
    CQ_ITEM *head;
    CQ_ITEM *tail;
    pthread_mutex_t lock;
    pthread_cond_t  cond;
};
typedef struct conn_queue CQ;

Why does the first version work?


You aren't really using the struct before it's defined, you're creating an synonym for it. Until you start doing something with the structure, the compiler doesn't need to know what it looks like.

Your typedef contains a predeclaration:

typedef **struct conn_queue** CQ;

When you start using the structure, the compiler will need to know what it looks like (sizeof, referencing member variables etc).

So, for the following code:

// This line is perfectly legal, even though foo is NEVER defined.
typedef struct foo fooType;

int main() {
  // If the following line is uncommented, an error will occur because:
  // storage size of ‘foo’ isn’t known
  // fooType foo;
  return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消