前言
简言之,为了增强代码可读性或减少代码的冗余,采用 typedef 给某个类型取个别名。
一、typedef 用于基本数据类型
typedef int u16;
typedef unsigned char uchar;
以后再用到 int ,unsigned char 时可用 u16 ,uchar 代替
二、typedef 用于结构体类型
typedef struct Student{
int sid;
int age;
char name[20];
}st;
st st1
上面代码中构造了一个新的数据类型,类型名为 “ struct Student”
其实上述用法是一种简写,完整表达,如下所示:
struct Student{
int sid;
int age;
char name[20];
};
typedef struct Student st;
st st1
三、typedef 用于枚举类型
typedef enum people{
male = 1,
female = 2,
}gender;
gender s2;
定义了一个新的数据类型,类型名“enmu people” ,结合 typedef 用法,下文可用gender 替换enum people;同理展开写如下所示
enum people{
male = 1,
female = 2,
};
typedef enum people gender;
gender s2;
四、typedef 用于数组
定义两个数组
char arr1[100];
char arr2[100];
也可以,这样
typedef char arr[100];
arr arr1,arr2;
总结
关于typedef关键字的用法还有很多,后续将继续与大家分享,与大家一块进步,以上内容欢迎指正!!
毕竟是复习,编了一段测试代码,随文附上!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int u16;
typedef struct Student{
int sid;
int age;
char name[20];
}st;
typedef enum people{
male = 1,
female = 2,
}gender;
int main(int argc, char *argv[])
{
u16 i = 8;
st mid_student;
st * pMid_student = &mid_student ;
pMid_student->sid = 124;
pMid_student->age = 12;
strcpy(pMid_student->name,"lihua");
gender s1 = male;
printf("%d \n ", i);
printf("%d %d %s \n",pMid_student->sid,pMid_student->age,pMid_student->name);
printf("%d", s1);
return 0;
}
|