typedef用法

1.8k words

良好的代码习惯高效的类型定义在项目中扮演着至关重要的角色。typedef,它不仅是一个语法糖,更是提升代码质量和可维护性的利器。在这篇文章中,将为你介绍typedef 4 种应用方式。

应用一、为基本数据类型定义新的类型名

uint32_t替代unsigned int声明变量

1
2
3
4
5
/* 变量名重定义 */
typedef unsigned int uint32_t;

/* 定义一个`unsigned int`类型的变量 */
uint32_t count = 0;

应用二、为自定义数据类型(结构体、共用体和枚举类型)定义简洁的类型名称

使用结构体定义以及声明结构体变量:

1
2
3
4
5
6
7
8
9
struct TagPoint
{
double x;
double y;
double z;
};/* 定义一个三维坐标结构体 */

/* 声明一个三维坐标点 */
struct TagPoint point = {0, 0, 0};

使用typedef代替结构体定义以及声明结构体变量:

1
2
3
4
5
6
7
8
9
typedef struct
{
double x;
double y;
double z;
} TagPoint;/* 定义一个三维坐标结构体 */

/* 声明一个三维坐标点 */
TagPoint point = {0, 0, 0};

应用三、定义数组类型

定义多个同纬度的数组:

1
2
int v[3];
int i[3];

使用typedef重定义:

1
2
3
4
5
/* 定义数组类型 */
typedef int arry_int_3[3];

/* 等价于 int v[3] */
arry_int_3 v;

应用四、定义指针类型

1、定义数组指针类型
1
2
3
4
5
6
7
8
9
10
/* 普通数组指针 */
int (*arr_p)[5];//定义了一个数组指针变量arr_p,arr_p可以指向一个int a[5]的一维数组

/* 使用typedef */
typedef int(*Arr_P)[5];//定义一个指针类型,该类型的指针可以指向含5个int元素的一维数组

int a[5] = {1,2,3,4,5};
Arr_P p;//定义数组指针变量p
p= &a;//完全合法,无警告
p= (Arr_P)&a;//类型强制转换为Arr_P,完全合法,无警告
2、定义函数指针类型

有一个函数原型如下:

1
2
3
/* 函数原型 */
int32_t write_adc_reg(uint32_t reg_addr, uint32_t data, uint32_t chip_id);
int32_t write_spi_reg(uint32_t reg_addr, uint32_t data, uint32_t chip_id);

普通定义一个函数指针指向这个函数:

1
2
3
4
5
6
7
8
9
/* 普通函数指针定义和使用 */
int32_t (*write_adc_reg_p)(uint32_t, uint32_t, uint32_t);
int32_t (*write_spi_reg_p)(uint32_t, uint32_t, uint32_t);

/* 选择不同的写入接口 */
write_adc_reg_p = write_adc_reg;
write_spi_reg_p = write_spi_reg;
/* 调用 */
int32_t result = write_reg_p(0x10, 0x55, 0);

使用typedef:

1
2
3
4
5
6
7
/* 定义函数指针类型 */
typedef int32_t (*WriteReg_P)(uint32_t, uint32_t, uint32_t);
/* 声明两个函数指针变量 */
WriteReg_P write_adc_reg_p = write_adc_reg;
WriteReg_P write_spi_reg_p = write_spi_reg;
/* 调用 */
int32_t adc_val = write_adc_reg_p(0x10, 0x55, 0);

五、总结

typedef 是 C 语言中非常实用的工具,它不仅能提升代码的可读性,还便于后续维护和扩展。在嵌入式开发中,通过合理使用 typedef,我们可以简化结构体、指针、函数指针等复杂类型的声明,让代码更清晰、表达更简洁。