一、概念
给数据类型定义一个新的名字
二、使用
1、基本数据类型
#include <stdio.h> typedef int Integer; // 给int起一个新的名字Integer后,int能正常使用 typedef Integer Integer2; // 在别名的基础上,再给Integer起一个新的名字Integer2 int main() { int i = 1; Integer i2 = 2; Integer2 i3 = 3; printf("%d, %d, %d\n", i, i2, i3); // 输出:1, 2, 3 return 0; }
2、指针
#include <stdio.h> typedef char * String; // 给char *起一个新的名字String int main() { String name = "hello"; printf("%s\n", name); // 输出:hello return 0; }
3、结构体
// 方式一 struct PersonType { char *name; }; typedef struct PersonType Person; // 方式二 typedef struct StudentType { char *name; } Student; // 方式三 typedef struct{ char *name; } Cat; int main() { // 方式一 Person p = {"hello"}; printf("%s\n", p.name); // 输出:hello // 方式二 Student stu = {"world"}; printf("%s\n", stu.name); // 输出:world // 方式三 Cat cat = {"world"}; printf("%s\n", cat.name); // 输出:world return 0; }
4、指向结构体的指针
#include <stdio.h> struct Person { char *name; }; typedef struct Person * PersonPoint; int main() { struct Person p = {"hello"}; PersonPoint pp = &p; pp->name = "world"; printf("%s\n", p.name); return 0; }
5、枚举
#include <stdio.h> /* // 方式一 enum SexEnum { Man, Woman, Unknow }; typedef enum SexEnum Sex; // 方式二 typedef enum SexEnum { Man, Woman, Unknow } Sex; */ // 方式三 typedef enum { Man, Woman, Unknow } Sex; int main() { Sex sex = Man; printf("%d\n", sex); return 0; }
6、指向函数的指针
#include <stdio.h> int sum(int v1, int v2) { return v1 + v2; } typedef int (*IntFunc)(int, int); int main() { IntFunc func = sum; printf("%d\n", func(3, 4)); return 0; }
三、#define与typedef
先看下面的代码
输出:#define String char * typedef char * String2; int main() { String s1 = "hello"; String2 s2 = "world"; printf("%s, %s\n", s1, s2); return 0; }
hello, world
这段代码大家都很容易理解,现在再看下面的代码
此时有什么区别呢?让我们来分析一下:#include <stdio.h> #define String char * typedef char * String2; int main() { String s1, s2; String2 s3, s4; return 0; }
String s1, s2; 因为String 是一个宏定义,编译预处理的时候会直接替换掉,也就相当于char *s1, s2;再明白点就是char *s1; char s2; 这个可以通过sizeof得到证明,只有s1 是char *类型,s2是char 类型。
String2 s3, s4; typedef 是给类型起一个别名,所以就等于 char *s3; char *s4; 所以s3, s4都是char *类型的。