typedef是C语言的关键字,其作用是为数据类型定义别名。
typedef int Integer;
typedef unsigned int UInterger;
typedef float Float;
int main() {
//用别名定义变量
Integer i = 2;
UInterger ui = 17;
Float f = 13.14f;
return 0;
}
1 typedef与指针
typedef不仅能为基本数据结构类型定义别名,还能为指针定义别名。除了基本类型指针,结构体指针以及指向函数的指针也能被定义别名。
typedef char *String;
// 定义一个结构体
struct Student {
int age;
float height;
};
// 起别名
typedef struct Student *pStudent;
// 定义一个sum函数
int sum(int a, int b)
{
return c = a + b;
}
//定义一个指向函数的指针的别名
typedef int (*pSum)(int, int);
int main(int argc, const char * argv[]) {
// 相当于char *str = "zhangsan";
String str = "zhangsan";
struct Student stu = {12,123.4f};
pStudent pStu = &stu; //结构体指针
pSum p = sum; //指向函数的指针
int a = (*p)(1,2);
return 0;
}
2 typedef与结构体,枚举
enum Season {spring, summer, autumn, winter};
// 给枚举类型起别名
typedef enum Season Season;
/*简化写法
typedef enum Season {spring, summer, autumn, winter} Season;
typedef enum {spring, summer, autumn, winter} Season;
*/
// 定义一个结构体
struct Student {
int age;
float height;
};
// 起别名
typedef struct Student Student;
/*简化写法
typedef struct Student {
int age;
float height;
} Student;
typedef struct {
int age;
float height;
} Student;
*/
int main(int argc, const char * argv[]) {
Season s = summer;
Student stu;
stu.age = 12;
return 0;
}