Typedef 结构与结构?|定义差异| [英] Typedef struct vs struct? |Definition difference|

查看:28
本文介绍了Typedef 结构与结构?|定义差异|的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下块位于 main() 和每个函数之前(全局范围)

第一块:

The following blocks are outside of main() and before every function (global scope)

1st block:

struct flight {
    int number;
    int capacity;
    int passengers;
};

有了这个,你可以创建数组、指针、变量,而不是写} var;(它只定义了这个自定义数据类型的一个变量(struct flight))

With this you can create array,pointer,variable in contrast with writing } var; (which defines only one variable of this custom data type (struct flight))

第二块:

typedef struct flight {
    int number;
    int capacity;
    int passengers;
} flight;

声明它会创建一个数据类型flight,而不必一直写struct flight
我的问题是为什么typedef需要在块的末尾再次写入flight?
这有点令人困惑(它看起来只是该数据类型的变量)

Declaring this creates a data type flight without having to write struct flight all the time
My question is why typedef needs flight to be written a second time at the end of a block?
which is a bit confusing (it looks like only a variable of that datatype)

推荐答案

我的问题是为什么 typedef 需要在块的末尾再次写入飞行?

My question is why typedef needs flight to be written a second time at the end of a block?

当您声明时:

typedef struct flight{
    int number;
    int capacity;
    int passengers;
 }flight;

你实际上声明了两件事:

you actually declare two things:

  • 一种新的结构类型struct flight
  • struct flight 的类型别名 flight.
  • a new structure type struct flight
  • a type alias name flight for struct flight.

与普通声明一样,带有 typedef 的类型别名出现在声明末尾的原因是因为历史原因 typedef 被放在了相同的说明符中category 作为存储类说明符(如 staticauto).

The reason why the type alias name with typedef appears at the end of the declaration like for any ordinary declaration is because for historical reasons typedef was put in the same specifiers category as storage-class specifiers (like static or auto).

请注意,您可以声明:

typedef struct {
    int number;
    int capacity;
    int passengers;
}flight;

如果您打算仅使用类型标识符 flight,则不要使用标签名称.

without the tag name if you intend to only use the type identifier flight.

这篇关于Typedef 结构与结构?|定义差异|的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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