C语言中typedef的用法

本文是参考谭浩强的《C程序设计》第二版一书所写,总感觉有些重点的地方书中没有提出来,等本人遇到其他重要用法的时候再来补充,或者大家帮我提出来,以便共同学习。

1、用typedef声明新的类型名来代替已有的类型名

 

[cpp] view plain copy

  1. typedef int INTEGER;  
  2. typedef float REAL;  

这样以下两行代码就可以等价替换了

[cpp] view plain copy

  1. int i,j;float a,b;  
  2. INTEGER i,j;REAL a,b;  

2、用typedef声明一个结构体

[cpp] view plain copy

  1. typedef struct  
  2. {int month;  
  3.   int day;  
  4.   int year;  
  5. }DATE;  

 

声明新类型名DATE,它代表上面指定的一个结构体类型,这时就可以用DATE定义变量。

[cpp] view plain copy

  1. DATE birthday  
  2. DATE *p  

其中birthday是一个结构体,具体内容同上DATE结构体。

下面举个例子,是在STM32单片机的流水灯程序中用到的一个结构体。

[cpp] view plain copy

  1. typedef struct  
  2. {  
  3.   uint16_t GPIO_Pin;             /*!< Specifies the GPIO pins to be configured. 
  4.                                       This parameter can be any value of @ref GPIO_pins_define */  
  5.   
  6.   GPIOSpeed_TypeDef GPIO_Speed;  /*!< Specifies the speed for the selected pins. 
  7.                                       This parameter can be a value of @ref GPIOSpeed_TypeDef */  
  8.   
  9.   GPIOMode_TypeDef GPIO_Mode;    /*!< Specifies the operating mode for the selected pins. 
  10.                                       This parameter can be a value of @ref GPIOMode_TypeDef */  
  11. }GPIO_InitTypeDef;  
  12.   
  13. GPIO_InitTypeDef GPIO_InitStructure;  

 

这里结构体又嵌套了一个2个结构体,GPIOSpeed_TypeDef、GPIOMode_TypeDef,他们有着跟本结构体相同的定义方式,我们来看一下:

 

 

[cpp] view plain copy

  1. typedef enum  
  2. {   
  3.   GPIO_Speed_10MHz = 1,  
  4.   GPIO_Speed_2MHz,   
  5.   GPIO_Speed_50MHz  
  6. }GPIOSpeed_TypeDef;  

 

[cpp] view plain copy

  1. typedef enum  
  2. { GPIO_Mode_AIN = 0x0,  
  3.   GPIO_Mode_IN_FLOATING = 0x04,  
  4.   GPIO_Mode_IPD = 0x28,  
  5.   GPIO_Mode_IPU = 0x48,  
  6.   GPIO_Mode_Out_OD = 0x14,  
  7.   GPIO_Mode_Out_PP = 0x10,  
  8.   GPIO_Mode_AF_OD = 0x1C,  
  9.   GPIO_Mode_AF_PP = 0x18  
  10. }GPIOMode_TypeDef;  


上面我们用GPIO_InitTypeDef GPIO_InitStructure来定义了一个GPIO_InitStructure结构体,他的元素跟GPIO_InitTypeDef一样,我们可以用下面的语句方式来对结构体进行填充

 

 

[cpp] view plain copy

  1. GPIO_InitStructure.GPIO_Pin = DS1_PIN|DS2_PIN|DS3_PIN|DS4_PIN;   
  2. GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;  
  3. GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;  


3、用typedef声明数组

 

如定义数组,原来用如下形式:

 

[cpp] view plain copy

  1. int a[10],b[10],c[10],d[10];  

由于都是一维数组,大小也相同,可以先将此数组类型声明为一个名字:然后用ARR区定义数组变量:

[cpp] view plain copy

  1. typedef int ARR[10];  
  2. ARR a,b,c,d;  
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值