1. 执行时间不同
-
关键字
typedef
在编译阶段有效,由于是在编译阶段,因此typedef
有类型检查的功能。 -
#define
则是宏定义,发生在预处理阶段,也就是编译之前,它只进行简单而机械的字符串替换,而不进行任何检查。
例1.1: typedef
会做相应的类型检查
typedef unsigned int UINT;
void func()
{
UINT value = "abc"; // error C2440: 'initializing' : cannot convert from 'const char [4]' to 'UINT'
cout << value << endl;
}
例1.2: #define
不做类型检查:
// #define用法例子:
#define f(x) x*x
int main()
{
int a=6, b=2, c;
c=f(a) / f(b);
printf("%d\n", c);
return 0;
}
程序的输出结果是: 36,根本原因就在于
#define
只是简单的字符串替换。
2. 功能有差异
-
typedef
用来定义类型的别名,定义与平台无关的数据类型,与