typedef struct vs struct definitions [重复]

本文探讨了在C语言中使用`typedef struct`与直接使用`struct`定义结构体的区别。主要区别在于`typedef`为结构体类型提供了一个别名,使得代码更加简洁,并且在后续引用时可以避免使用`struct`关键字。不使用`typedef`时,每次声明结构体变量都需要使用`struct`前缀。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自: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前缀。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值