4.4.1 C语言的2种类型:内建类型与用户自定义类型
(1)内建类型ADT、自定义类型UDT
4.4.2 typedef定义(或者叫重命名)类型而不是变量
(1)类型是一个数据的模板,变量是一个实在的数据。类型是不占内存的,而变量是占内存的。
(2)面向对象的语言中,类型就是类class,变量就是对象。
4.4.3 typedef与#define宏的区别
typedef char *pchar;
#define pchar char *
4.4.4 typedef与结构体
(1)结构体在使用时都是先定义结构体类型,再用结构体的类型去定义变量。
(2)C语言语法规定,结构体类型使用时必须是struct 结构体类型名 结构体变量名;这样的方式来定义变量;
(3)使用typedef一次定义2个类型,分别是结构体变量类型,和结构体变量指针类型。
#include <stdio.h>
//结构体类型的定义,这个类型有2个名字:第一个名字是struct student,第二个类型名叫strudent_t
//定义了2个类型,第一个是结构体类型,有2个名字;
//第二个是结构体指针类型,有2个名字,第一个struct student *,pStudent
typedef struct student
{
char name[20];
int age;
} student_t,*pStudent;
int main(void)
{
struct student s1; //struct student是类型;s1是变量
student_t s2;
struct student *ps1; //结构体指针
student_t *ps2;
pStudent p1 = &s2;
return 0;
}
4.4.5 typedef与const
(1)typedef int *PINT; //const PINT p2;相当于是int *const p2;
(2)typedef int *PINT; //PINT const p2;也相当于是int *const p2;
(3)如果确实想得到const int *p;这种效果,只能typedef const int *CPINT;
#include <stdio.h>
typedef int *PINT; //const PINT p2;相当于是int *const p2;
//PINT const p2;也相当于是int *const p2;
//const int * 和 int *const p是不同的。前者是p指向的变量是const,后者是p本身const
int main(void)
{
int a = 23;
int b = 10;
PINT p1 = &a; //const PINT p2 = &a;
//等价于int * const p2;
PINT const p2 = &a; //跟上一行代码是一样的执行结果
*p2 = 32;
printf("*p2 = %d\n",*p2);
p2 = &b; //assignment of read-only variable ‘p2’
return 0;
}
4.4.6 使用typedef的重要意义(2个:简化类型、创造平台无关类型)
(1)简化类型的描述。如:typedef char *(*pFunc)(char *,char *) ;
(2)很多编程体系下,人们倾向于不使用int,double等C语言内建类型,因为这些类型本身和平台是相关的(譬如int在16位机器上是16位的,在32位机器上就是32位的)。为了解决这个问题,很多程序使用自定义的中间类型来做缓冲。譬如Linux内核种大量使用了这种技术。内核中先定义:typedef int size_t;然后在特定的编码需要下用size_t来替代int(譬如可能还有typedef int len_t)
(3)STM32的库中全部使用了自定义类型,譬如typedef volatile unsigned int vu32;
本文详细介绍了C语言中的内建类型与用户自定义类型(如typedef和结构体),区分typedef和#define宏,并展示了如何使用typedef简化类型定义及创建平台无关类型。通过实例探讨了const与typedef的结合,以及typedef在实际编程中的重要应用,如类型重命名和跨平台数据处理。
123

被折叠的 条评论
为什么被折叠?



