typedef在编程中随处可见,大家都知道,它的作用无非有如下两种:
1、让代码更加简洁
2、让代码更加直观
3、其它更深层次的用途????
如下面的例子:
#include <stdio.h>
#include <stdlib.h>
struct point
{
int x;
int y;
};
struct point* AddPoint(struct point *p1, struct point *p2)
{
p1->x += p2->x;
p1->y += p2->y;
return p1;
}
int main()
{
struct point p1 = {10, 20};
struct point p2 = {30, 40};
struct point TheAddPoint = *(AddPoint(&p1, &p2));
printf("TheAddPoint x is %d y is %d", TheAddPoint.x, TheAddPoint.y);
return 0;
}
那么用typedef,自定义两个别名(而非新建数据类型,注意是别名):
typedef struct point Point;
typedef struct point *PointPtr;
整个代码就可以改为:
#include <stdio.h>
#include <stdlib.h>
struct point
{
int x;
int y;
};
typedef struct point Point;
typedef struct point *PointPtr;
/*
struct point* AddPoint(struct point *p1, struct point *p2)
{
p1->x += p2->x;
p1->y += p2->y;
return p1;
}
*/
PointPtr AddPoint(PointPtr p1, PointPtr p2)
{
p1->x += p2->x;
p1->y += p2->y;
return p1;
}
int main()
{
/*
struct point p1 = {10, 20};
struct point p2 = {30, 40};
struct point TheAddPoint = *(AddPoint(&p1, &p2));
*/
Point p1 = {10, 20};
Point p2 = {30, 40};
Point TheAddPoint = *(AddPoint(&p1, &p2));
printf("TheAddPoint x is %d y is %d", TheAddPoint.x, TheAddPoint.y);
return 0;
}
接下来,我们再来考虑其深层次的用途。