1、关键字typedef可以为各种数据类型定义一个新的名字(别名)
typedef int Integer; // 为int起个别名叫Integer
Integer i = 0; // 相当于 int i = 0;
2、给指针定义一个别名
// 之前我们是这样定义一个指针的
char *s = "cobish";
// ----------------------------
// 现在可以这样
typedef char * String;
String s = "cobish";
3、给结构体起别名
// 之前我们是这样定义结构体的
struct Point {
int x;
int y;
};
struct Point p = {3, 4};
// --------------------------------------------------------
// 现在可以这样,给结构体Point起个别名叫MyPoint
typedef struct Point {
int x;
int y;
} MyPoint;
MyPoint p = {3, 4};
// --------------------------------------------------------
// 当然结构体Point名字这时就可以省略了
typedef struct {
int x;
int y;
} MyPoint;
MyPoint p = {3, 4};
4、给结构体指针起别名
typedef struct Point {
int x;
int y;
} * PP;
struct Point p = {3, 4};
PP pp = &p;
printf("x=%d\n", pp->x); // 输出:x = 3
// --------------------------------------------------------
// 或者可以先给结构体起别名,再给结构体指针起别名
typedef struct Point {
int x;
int y;
} MyPoint;
typedef MyPoint * PP;
MyPoint p = {3, 4};
PP pp = &p;
printf("x=%d\n", pp->x); // 输出:x = 3
5、给枚举起别名
// 原先
eumn Season {spring, summer, autumn, winter};
eumn Season s = spring;
// --------------------------------------------------------
typedef eumn Season {
spring,
summer,
autumn,
winter
} MySeason;
MySeason s = spring;
// --------------------------------------------------------
// 可省略枚举名
typedef eumn {
spring,
summer,
autumn,
winter
} Season;
Season s = spring;
6、typedef 与 #define 的区别
// 虽然这两个看起来很像
typedef char * String;
#define String char *;
String s1 = "cobish";
// --------------------------------------------------------
// 但实际来说,#define只是纯粹的字符串替换
typedef char * String;
String s1, s2; // 等同于 char *s1; char *s2;
#define String char *;
String s1, s2; // 等同于 char *s1; char s2;