C语言中为数据类型定义一个别名:typedef

typedef


作用:为各种数据类型定义一个别名

使用方式


与基本数据类型

1
2
typedef int Integer; //别名为Integer
Integer a = 8;
  • 别名的别名
1
2
typedef Integer MyInteger;
MyInteger aa = 8;

与指针

1
2
typedef char* String;
String str = "stone";

与结构体

1
2
typedef struct Person Per;// 这样在定义结构体变量时 就不用带上struct 关键字了
Per p = {...};
  • 定义并取别名
1
2
3
4
5
6
7
8
typedef struct Student {
int age;
} Stu;
void processStudent() {
Stu student = {18};
student.age =19;
}

与指向结构体的指针

1
2
3
4
5
6
7
8
9
typedef struct {
int age;
} Stu;
Stu stu = {20};
typedef Stu *S; //指向结构体的指针 取别名 S
S s = &stu;

又例:

1
2
3
4
5
6
7
8
9
10
11
12
13
typedef struct LNode {
int data;
struct LNode *next;//LNode的指针变量
} LinkList, *SList;
LinkList l = {1, NULL};
LinkList ll = {2, NULL};
l.next = ≪
printf("%d, ", l.next->data);
SList sl = ≪
if (sl->next != NULL)
printf("%d, ", sl->data);

与枚举

与结构体的使用是一样的。这里来一个复杂点的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
typedef enum LNode {
A = 10, B
} Node, *Pn;
// 没有typedef定义时,Node是枚举类型LNode的变量名,Pn是指针变量名
// Node = B;
// Pn = &Node;
//有typedef定义时,Node是枚举类型LNode的别名,Pn是指针类型别名
Node node = A;
printf("%d\n", node);
Pn pp = &node;
printf("%d\n", *pp);

与数组

1
2
3
typedef char line[5];//表示定义一个长度为5的char类型数组 的别名 为 line
line l = {'a','b','c', 'd', '\0'};
printf("%s", l);

与指针常量

1
2
3
4
5
6
7
typedef int * Px;
//这时Px 就是 int型的指针类型
//要声明常量
const Px p1; //error,编译器可能会解释成:int * const
//正确形式:
typedef const int * Px;

与函数、函数指针

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void test(int* value, void* savedState, size_t savedStateSize) {
printf("%d\n", *value);
}
int main(int argc, char *argv[]) {
typedef void mf(int*, void*, size_t); //函数别名mf
mf *a = test;
int c = 80;
a(&c, NULL, 0);
typedef void (*mx)(); //函数指针别名 mx
mx m = test;
c = 81;
m(&c, NULL, 0);
}

typdef与#define的区别


#define 是用来定义宏的。而宏的语义就是在预编译时,用宏定义后的字符串来替换宏名。

如,

typedef char* String;, 可以用宏来替换 #define String char*

但是,像一些复杂的别名定义,如与结构体、枚举等这样的 复合类型的定义,就不能直接使用#define来定义了。当然,若是分段来定义,还是可以的。结合上面枚举的例子,如:

1
2
#define M enum LNode
M node = B;
------ 本文结束 ------

版权声明
协议:No Fuck License

stone 创作并维护
本文首发于 stone世界 博客( http://stone86.top
版权所有,侵权必究。如要转载,请声明出处

Fork me on GitHub