嗯,这倒不算是创建新的类型,更像是为已有类型取了个新名字。

表面上看起来有点没什么意义,但我们其实可以利用这一点让代码看起来更整洁、更清晰。

10.1 typedef in Theory

基本上,你就是拿一个已有的类型,用 typedef 为它起一个别名。

比如这样:

typedef int antelope;    // 把 "antelope" 作为 "int" 的别名

antelope x = 10;         // 类型 "antelope" 就相当于 "int"

你可以对任何已有类型这样做。甚至可以用逗号一次定义多个类型别名:

typedef int antelope, bagel, mushroom;   // 它们都是 "int"

这真的很有用,对吧?你可以输入 mushroom 代替 int,这个功能一定让你超级兴奋吧!

好啦,讽刺教授,我们马上来看它更常见的一些应用。

10.1.1 Scoping

typedef 遵循常规的作用域规则。

因此,很常见的做法是在文件作用域(“全局”)使用 typedef,这样所有函数都可以随意使用这些新类型。

10.2 typedef in Practice

所以把 int 重命名成别的名字并不是特别有趣。

我们来看看 typedef 通常会用在哪些地方。

10.2.1 typedef and structs

有时候会用 typedef 给一个 struct 取个新名字,这样你就不用一次次地写 struct 这个词了。

struct animal {
    char *name;
    int leg_count, speed;
};

//    原始名称    新名称
//       |         |
//       v         v
//       /----------/ /----/
typedef struct animal animal;

struct animal y;      // 这样写是可以的
animal z;             // 这样写也可以,因为 "animal" 是一个别名

就我个人而言,我并不喜欢这种做法。我喜欢代码中明确写出 struct,因为程序员可以一眼明白类型是什么。但这确实很常见,所以我在这里也提一下。