typedef和define都是给对象取一个别名,以增强程序的可读性,但二者却有许多不同的地方:
(1)用法不同
typedef用来定义一种数据类型的别名;
如:typedef int Status;
define用来定义常量,或者用来代替的表达式;
如:define MAX(a,b) ((a>b)?(a):(b))
(2) 执行时间不同
typedef是编译过程的一部分,有类型检查功能;define是宏定义,是预编译过程,只是进行简单的字符替换,没有类型检查功能。
(3) 作用域不同
typedef有作用域限制,而define不受约束,只要在define声明后的引用均可。
(4)对指针的引用不同
如:
typedef int * pint;
#define PINT int *;
Const pint p; // p不可更改,p指向的内容可以更改,相当于 int * const p;
Const PINT p; // p可以更改,p指向的内容不能更改,相当于 const int *p;或 int const *p;
pint s1,s2; //s1,s2都是指针
PINT s1,s2; // s1是指针,s2是整型变量