c语言学习--typedef取别名
typedef是用来给类型去别名的
用法:
typedef 原类型 新类型
#include<stdio.h> #include<stdlib.h> //typedef变量取别名 int main (void) { int a = 10; typedef int u32; //typedef 原类型名 新类型名 u32 b = 20; printf("u32 is %d \n",b); printf("the sizeof u32 is %d\n", sizeof(u32)); printf("int is %d\n",a); }
u32 is 20
the sizeof u32 is 4
int is 10
#include<stdio.h> #include<stdlib.h> //typedef 结构体取别名 struct stu { int a; int b; }; typedef struct stu ST; int main (void) { struct stu T1 = {1,2}; printf("T1.a %d T1.b %d \n", T1.a, T1.b); ST T2 = {12,34}; // ST == struct stu printf("T2.a %d T2.b %d \n", T2.a, T2.b); } T1.a 1 T1.b 2 T2.a 12 T2.b 34
#include<stdio.h> /* struct person { int id; int age; }; typedef struct person ps; */ //下面这段代码和上面的代码是等效的, 使用typedef来去别名 typedef struct person { int id; int age; }ps; int main() { ps p1 = {1,2}; //定义并初始化一个结构体变量p1 printf("%d , %d",p1.id,p1.age); } 1,2
typedef可以用来区分数据类型
#include<stdio.h> int main() { char* p1, p2; //p1 是char*, p2是char //可以通过sizeof来判断 printf("%d \n",sizeof(p1)); printf("%d \n",sizeof(p2)); typedef char* CHAR; CHAR p3, p4;//这样p3, p4 都是char* 数据类型了 printf("%d \n",sizeof(p3)); printf("%d \n",sizeof(p4)); } 8 1 8 8