struct conn_queue 在定义之前如何使用?

发布于 2024-11-09 12:18:37 字数 391 浏览 0 评论 0原文

这段代码有效:

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

我认为应该是这样的:

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

为什么第一个版本有效?

This code works:

typedef struct conn_queue CQ;
struct conn_queue {
    CQ_ITEM *head;
    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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆沫 2024-11-16 12:18:37

在定义结构之前,您并没有真正使用该结构,而是为其创建了一个同义词。在您开始对结构进行操作之前,编译器不需要知道它是什么样的。

你的 typedef 包含一个预声明:

typedef **struct conn_queue** CQ;

当你开始使用结构时,编译器需要知道它是什么样的(sizeof、引用成员变量等)。

因此,对于以下代码:

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文