C typedef 关键字
C typedef
typedef 关键字允许您为现有类型创建一个新名称(别名)。
这可以使复杂的声明更容易阅读,并使你的代码更容易维护。
例如,与其总是写float,我们可以创建一个名为Temperature的新类型,使代码更清晰:
示例
#include <stdio.h>
typedef float Temperature;
int main() {
Temperature today = 25.5;
Temperature tomorrow = 18.6;
printf("Today: %.1f C", today);
printf("Tomorrow: %.1f C", tomorrow);
return 0;
}
亲自试一试 »
这里,Temperature 只是 float 的另一种说法。然而,这段代码更具表达力:它告诉我们这些数字是温度,而不仅仅是任何浮点数。
为什么要使用 typedef?
- 简化代码:更短、更易读的类型名称。
- 提高清晰度:更好地表达意图(例如,使用
AGE而不是int)。此外,当多个变量共享相同的基本类型时(例如float或double),也有助于避免混淆。
值得了解:在现代 C 语言中,typedef 通常与 struct、enum 和函数指针一起使用,以保持代码的简洁性和可读性。
使用结构体定义 typedef
typedef 与 struct 结合使用非常有用,因为它能让你避免每次都编写 struct:
示例
#include <stdio.h>
// Without typedef:
struct Car {
char brand[30];
int year;
};
// With typedef:
typedef struct {
char brand[30];
int year;
} Car;
int main() {
struct Car car1 = {"BMW", 1999}; // needs "struct"
Car car2 = {"Ford", 1969}; // shorter with typedef
printf("%s %d", car1.brand, car1.year);
printf("%s %d", car2.brand, car2.year);
return 0;
}
亲自试一试 »
此示例展示了如何通过 typedef 简化对多个结构体变量(例如不同的汽车型号)的处理:
示例
#include <stdio.h>
// With typedef
typedef struct {
char brand[30];
char model[30];
int year;
} Car;
int main() {
Car car1 = {"BMW", "X5", 1999};
Car car2 = {"Ford", "Mustang", 1969};
Car car3 = {"Toyota", "Corolla", 2011};
printf("%s %s %d", car1.brand, car1.model, car1.year);
printf("%s %s %d", car2.brand, car2.model, car2.year);
printf("%s %s %d", car3.brand, car3.model, car3.year);
return 0;
}
亲自试一试 »
在这里你可以看到,当结构体嵌套在其他结构体中时,typedef 是如何保持代码简洁的:
示例
#include <stdio.h>
// 使用 typedef 定义三个结构体
typedef struct {
char firstName[20];
char lastName[20];
} Owner;
typedef struct {
char brand[20];
int year;
Owner owner;
} Car;
typedef struct {
char name[30];
Car featuredCar;
} Dealership;
int main() {
Owner person = {"John", "Doe"};
Car car1 = {"Toyota", 2010, person};
Dealership d = {"City Motors", car1};
printf("Dealership: %s", d.name);
printf("Featured Car: %s (%d), owned by %s %s",
d.featuredCar.brand,
d.featuredCar.year,
d.featuredCar.owner.firstName,
d.featuredCar.owner.lastName);
return 0;
}
亲自试一试 »
是否使用typedef完全取决于您。
即使不使用,您的代码也能正常运行。但是,在现代 C 语言中,它通常用于使代码更简洁、更清晰、更易于维护。

