[英]typedef vs. no typedef with structs and enums in C
In C, is there any effective difference between declaring a struct as 在C中,将结构声明为是否存在任何有效差异
typedef struct {...} Foo;
and 和
struct Foo {...};
I know the second requires you to prefix uses with struct
, but what are the differences between these two definitions that I'll notice when writing or executing the program? 我知道第二个要求你使用
struct
作为前缀,但是在编写或执行程序时我会注意到这两个定义之间有什么区别? What about with enum
s? enum
怎么样?
Update: please see comments attached to answer for clarification. 更新:请参阅答案中的评论以获得澄清。
Original post. 原帖。
Besides having to write "struct" everywhere , something else of note is that using a typedef will allow you to avoid subtle syntax errors when working with pointers : 除了必须在任何地方编写“struct”之外 ,另外需要注意的是使用typedef 可以避免在使用指针时出现细微的语法错误 :
Quote: 引用:
Typedefs can also simplify declarations for pointer types. Typedef还可以简化指针类型的声明。 Consider this:
考虑一下:
struct Node {
int data;
struct Node *nextptr;
};
Using typedef, the above code can be rewritten like this: 使用typedef,可以像下面这样重写上面的代码:
typedef struct Node Node;
struct Node {
int data;
Node *nextptr;
};
In C, one can declare multiple variables of the same type in a single statement, even mixing pointer and non-pointers. 在C中,可以在单个语句中声明多个相同类型的变量,甚至可以混合指针和非指针。 However, one would need to prefix an asterisk to each variable to designate it as a pointer.
但是,需要在星号前加上每个变量的前缀,以将其指定为指针。 In the following, a programmer might assume that errptr was indeed a Node *, but a typographical error means that errptr is a Node.
在下文中,程序员可能会认为errptr确实是Node *,但是打字错误意味着errptr是一个Node。 This can lead to subtle syntax errors.
这可能会导致细微的语法错误。
struct Node *startptr, *endptr, *curptr, *prevptr, errptr, *refptr;
By defining a Node * typedef, it is assured that all the variables will be pointer types. 通过定义Node * typedef,可以确保所有变量都是指针类型。
typedef struct Node *NodePtr;
...
NodePtr startptr, endptr, curptr, prevptr, errptr, refptr;
If you write 如果你写
typedef struct {...} foo;
It saves you from having to write struct foo
everywhere: you can just write foo
. 它使您无需在任何地方编写
struct foo
:您只需编写foo
。
(You get this notational convenience for free in C++ by the way). (顺便说一句,你可以在C ++中免费获得这种符号方便性)。
我会看一下这个问题 ,然后总结一下struct { ... }
和typedef struct { ... }
之间没有明显的功能差异,尽管如果正确使用后者可能会使你的代码变得更简单,更容易理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.