良好的代码习惯和高效的类型定义在项目中扮演着至关重要的角色。typedef
,它不仅是一个语法糖,更是提升代码质量和可维护性的利器。在这篇文章中,将为你介绍typedef
4 种应用方式。
应用一、为基本数据类型定义新的类型名
用uint32_t
替代unsigned int
声明变量
1 2 3 4 5
| typedef unsigned int uint32_t;
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};
|
应用三、定义数组类型
定义多个同纬度的数组:
使用typedef重定义:
1 2 3 4 5
| typedef int arry_int_3[3];
arry_int_3 v;
|
应用四、定义指针类型
1、定义数组指针类型
1 2 3 4 5 6 7 8 9 10
| int (*arr_p)[5];
typedef int(*Arr_P)[5];
int a[5] = {1,2,3,4,5}; Arr_P p; p= &a; p= (Arr_P)&a;
|
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
,我们可以简化结构体、指针、函数指针等复杂类型的声明,让代码更清晰、表达更简洁。