typedef struct vs struct definitions [重复]

本文翻译自:typedef struct vs struct definitions [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

I'm a beginner in C programming, but I was wondering what's the difference between using typedef when defining a structure versus not using typedef . 我是C编程的初学者,但我想知道在定义结构时使用typedef与不使用typedef什么区别。 It seems to me like there's really no difference, they accomplish the same goal. 在我看来,它们之间并没有什么区别,它们实现了相同的目标。

struct myStruct{
    int one;
    int two;
};

vs.

typedef struct{
    int one;
    int two;
}myStruct;

#1楼

参考:https://stackoom.com/question/71pn/typedef-struct-vs-struct-definitions-重复


#2楼

The following code creates an anonymous struct with the alias myStruct : 以下代码创建一个别名为myStruct的匿名结构:

typedef struct{
    int one;
    int two;
} myStruct;

You can't refer it without the alias because you don't specify an identifier for the structure. 没有别名,就不能引用它,因为您没有为结构指定标识符。


#3楼

The typedef , as it is with other constructs, is used to give a data type a new name. 与其他构造一样, typedef用于为数据类型赋予新名称。 In this case it is mostly done in order to make the code cleaner: 在这种情况下,通常是为了使代码更整洁:

struct myStruct blah;

vs.

myStruct blah;

#4楼

In C (not C++), you have to declare struct variables like: 在C(不是C ++)中,您必须声明结构变量,例如:

struct myStruct myVariable;

In order to be able to use myStruct myVariable; 为了能够使用myStruct myVariable; instead, you can typedef the struct: 相反,您可以typedef结构:

typedef struct myStruct someStruct;
someStruct myVariable;

You can combine struct definition and typedef s it in a single statement which declares an anonymous struct and typedef s it. 您可以将struct定义和typedef组合在一个声明匿名structtypedef的语句中。

typedef struct { ... } myStruct;

#5楼

The difference comes in when you use the struct . 使用struct时会有所不同。

The first way you have to do: 您必须做的第一种方式:

struct myStruct aName;

The second way allows you to remove the keyword struct . 第二种方法允许您删除关键字struct

myStruct aName;

#6楼

If you use struct without typedef , you'll always have to write 如果使用不带typedef struct ,则始终必须编写

struct mystruct myvar;

It's illegal to write 写是非法的

mystruct myvar;

If you use the typedef you don't need the struct prefix anymore. 如果使用typedef ,则不再需要struct前缀。

发布了0 篇原创文章 · 获赞 137 · 访问量 84万+

猜你喜欢

转载自blog.csdn.net/xfxf996/article/details/105433451
今日推荐