typedef int* pint; //发生在编译时
相当于个int*起了一个别名,以后可以用来定义整型指针,也是一个类型名了。
pint p,q; //p,q都是指向int型的指针
而#define pINT int* //发生在预编译阶段
只做简单的宏替换
如pINT p,q
替换为int*p,q; //p是指针,而q只是一个整型变量
typedef并不是简单的替换
在MSDN中的解释如下:
A typedef declaration is a declaration with typedef as the storage class. The declarator becomes a new type. You can use typedef declarations to construct shorter or more meaningful names for types already defined by C or for types that you have declared. Typedef names allow you to encapsulate implementation details that may change.
A typedef declaration is interpreted in the same way as a variable or function declaration, but the identifier, instead of assuming the type specified by the declaration, becomes a synonym for the type.
但同时becomes a synonym for the type 原来类型的同义词?(我的英语没学好)
那么可不可以这样typedef INT int
然后 unsigned INT a=1; //当做和unsigned int a=1一样,答案是不可以
这样在vc2010中无法通过。我的理解是unsigned int 是一种类型,也可以写成unsigned,
而int也是一种类型,unsigned int 类型不是unsigned类型和int的组合,因为int是有符号的,前者是无符号的。
INT是一种新类型(前面(1)说了),unsigned INT企图组合两种类型肯定会出错。
unsigned int 为什么可以?因为它本身是一种数据类型,不是两种数据类型的组合。
前面说了typedef发生在编译时,编译器这时遇到unsigned INT它不认识,它只认识unsigned int
而#define INT int
unsigned INT 在预编译阶段发生简单的替换为unsigned int ,到了编译阶段,编译器见到的是unsigned int当然没问题
关键是要理解unsigned int是一个数据类型而不是两种数据类型unsigned 和int的组合