声明 C 结构的语法正确的方法是什么? [英] What's the syntactically proper way to declare a C struct?

查看:29
本文介绍了声明 C 结构的语法正确的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前见过 C 结构体声明了几种不同的方式.为什么会这样,如果有的话,每个人的行为有何不同?

I've seen C structs declared several different ways before. Why is that and what, if anything, does each do different?

例如:

struct foo {
  short a;
  int b;
  float c;
};

typedef struct {
  short d;
  int e;
  float f;
} bar;

typedef struct _baz {
  short a;
  int b;
  float c;
} baz;

int main (int argc, char const *argv[])
{
  struct foo a;
  bar b;
  baz c;

  return 0;
}

推荐答案

嗯,明显的区别体现在你的 main 中:

Well, the obvious difference is demonstrated in your main:

struct foo a;
bar b;
baz c;

第一个声明是未typedefed struct 并且需要使用struct 关键字.第二个是typedefed 匿名struct,因此我们使用typedef 名称.第三个结合了第一个和第二个:您的示例使用了 baz(很方便),但可以很容易地使用 struct _baz 达到相同的效果.

The first declaration is of an un-typedefed struct and needs the struct keyword to use. The second is of a typedefed anonymous struct, and so we use the typedef name. The third combines both the first and the second: your example uses baz (which is conveniently short) but could just as easily use struct _baz to the same effect.

更新:larsmans 的回答 提到了一种更常见的情况,您必须至少使用 struct x { } 来创建链表.第二种情况在这里是不可能的(除非你放弃理智并使用 void * 代替),因为 struct 是匿名的,而 typedef> 在定义 struct 之前不会发生,这使您无法创建指向 struct 类型本身的(类型安全)指针.第一个版本适用于这种用途,但根据我的经验,通常更喜欢第三个版本.为此给他一些代表.

Update: larsmans' answer mentions a more common case where you have to use at least struct x { } to make a linked list. The second case wouldn't be possible here (unless you abandon sanity and use a void * instead) because the struct is anonymous, and the typedef doesn't happen until the struct is defined, giving you no way to make a (type-safe) pointer to the struct type itself. The first version works fine for this use, but the third is generally preferred in my experience. Give him some rep for that.

更细微的区别在于命名空间的放置.在 C 中,struct 标签与其他名称放在一个单独的命名空间中,但 typedef 名称不是.所以以下是合法的:

A more subtle difference is in namespace placement. In C, struct tags are placed in a separate namespace from other names, but typedef names aren't. So the following is legal:

struct test {
  // contents
};

struct test *test() {
  // contents
}

但以下不是,因为 test 的名称会产生歧义:

But the following is not, because it would be ambiguous what the name test is:

typedef struct {
  // contents
} test;

test *test() {
  // contents
}

typedef 使名称更短(总是一个加号),但它将它放在与变量和函数相同的命名空间中.通常这不是问题,但它是一种超越简单缩短的细微差别.

typedef makes the name shorter (always a plus), but it puts it in the same namespace as your variables and functions. Usually this isn't an issue, but it is a subtle difference beyond the simple shortening.

这篇关于声明 C 结构的语法正确的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆