在 typedef struct 中指定结构名称
Specify struct name in typedef struct
有什么区别:
typedef struct{
uint8 index;
uint8 data[256];
}list_t;
list_t myList;
和
typedef struct list_t{
uint8 index;
uint8 data[256];
}list_t;
list_t myList;
我使用的是第一种方法,但我在答案中看到了第二种方法。我只想定义类型并分别定义具有该类型的变量。
第二种方法允许您转发声明结构类型。因此,如果我们正在处理 headers,您可以避免不必要的传递包含。例如,考虑这个小 header:
// No need to include the header with the full struct definition
// A forward declaration will do
struct list_t;
void foo(struct list_t *);
void bar(void); // Doesn't use list_t
这消除了对所有客户端代码的 list_t
完整定义的依赖。只需要使用 bar
的代码不会强制包含 list_t
的定义(通过传递包含)。
当您使用第一种方法时,您会为没有标记的结构类型创建一个别名,因此您不能 向前声明它。客户端代码强制包含您的类型定义以访问其名称。
差异对于自引用数据结构很有用。
typedef struct
{
int value;
Example1 *ptr; // error here: the type Example1 is not known yet
} Example1;
typedef struct Example2
{
int value;
struct Example2 *ptr; // OK: the type struct Example2 is known
} Example2;
请注意 struct
之后的名称不一定与用于 typedef
的名称相同。
这似乎是品味和首选编码风格的问题,但第二种方式(如其他答案中所述)对于自引用结构(例如列表或树数据结构)和前向声明很有用。
至于我,我更喜欢 C 中的第二种方式,并且认为它更常见。
在 C:
[typedef] struct [struct_name]
{
type attribute;
type attribute2;
// ...
[struct struct_name *struct_instance;]
} [struct_name_t] [struct_instance];
在这种情况下,有两种选择:第一种是省略 typedef
和 struct_name_t
,在这种情况下,要声明一个结构,您需要实际包含 struct
关键词:
struct struct_name struct_instance;
或者您可以使用 typedef
来声明您可以使用的 struct_name_t 类型:
struct_name_t struct_instance;
在任何一种情况下,如果您希望在结构内部声明一个指向结构的指针,您必须使用第一种语法,使用关键字 struct:
struct struct_name *struct_instance;
有什么区别:
typedef struct{
uint8 index;
uint8 data[256];
}list_t;
list_t myList;
和
typedef struct list_t{
uint8 index;
uint8 data[256];
}list_t;
list_t myList;
我使用的是第一种方法,但我在答案中看到了第二种方法。我只想定义类型并分别定义具有该类型的变量。
第二种方法允许您转发声明结构类型。因此,如果我们正在处理 headers,您可以避免不必要的传递包含。例如,考虑这个小 header:
// No need to include the header with the full struct definition
// A forward declaration will do
struct list_t;
void foo(struct list_t *);
void bar(void); // Doesn't use list_t
这消除了对所有客户端代码的 list_t
完整定义的依赖。只需要使用 bar
的代码不会强制包含 list_t
的定义(通过传递包含)。
当您使用第一种方法时,您会为没有标记的结构类型创建一个别名,因此您不能 向前声明它。客户端代码强制包含您的类型定义以访问其名称。
差异对于自引用数据结构很有用。
typedef struct
{
int value;
Example1 *ptr; // error here: the type Example1 is not known yet
} Example1;
typedef struct Example2
{
int value;
struct Example2 *ptr; // OK: the type struct Example2 is known
} Example2;
请注意 struct
之后的名称不一定与用于 typedef
的名称相同。
这似乎是品味和首选编码风格的问题,但第二种方式(如其他答案中所述)对于自引用结构(例如列表或树数据结构)和前向声明很有用。 至于我,我更喜欢 C 中的第二种方式,并且认为它更常见。
在 C:
[typedef] struct [struct_name]
{
type attribute;
type attribute2;
// ...
[struct struct_name *struct_instance;]
} [struct_name_t] [struct_instance];
在这种情况下,有两种选择:第一种是省略 typedef
和 struct_name_t
,在这种情况下,要声明一个结构,您需要实际包含 struct
关键词:
struct struct_name struct_instance;
或者您可以使用 typedef
来声明您可以使用的 struct_name_t 类型:
struct_name_t struct_instance;
在任何一种情况下,如果您希望在结构内部声明一个指向结构的指针,您必须使用第一种语法,使用关键字 struct:
struct struct_name *struct_instance;