typedef
作用: 给一个数据类型起一个别名。使得编程时较简单规范。其中有一点需要注意,如
typedef char* pstr2;
char string[4];
const char * pstr1=string;
const pstr2=string;
pstr1++;
pstr2++;
这里会在pstr2++处报错。原因是pstr2是const类型,不能进行修改。pstr2并不等于char*,typedef用于定义新类型。
typeof
作用:获得变量的类型。需要注意的是,typedef和typeof很像,在可以使用typedef的场合都可以使用typeof。typeof举例:
(1)
int (*a)();
typeof(a)b;
a是一个返回值为int型的函数指针,通过typeof获得a的类型,然后定义b,这样就定义了b是一个返回值为int型的函数指针。
(2)
typeof(int *) p1,p2; /* Declares two int pointers p1, p2 */
等同于 int *p1, *p2;
(3)
typeof(int [10]) a1, a2;/* Declares two arrays of integers */
等同于 int a1[10], a2[10];
一般情况下用typeof就可以,但如果要与ISO C保持兼容的话,最好是用双下划线的形式:__typeof__。
使用typeof的声明限制
请注意,typeof构造中的类型名不能包含存储类说明符,如extern或static。不过允许包含类型限定符,如const或volatile。
例如,下列代码是无效的,因为它在typeof构造中声明了extern:
typeof(extern int) a;
下列代码使用外部链接来声明标识符b是有效的,表示一个int类型的对象。下一个声明也是有效的,它声明了一个使用const限定符的char类型指针,表示指针p不能被修改。
extern typeof(int) b;
typeof(char * const) p = "a";
typeof在宏中使用特别方便,如实现所有数据类型的交换操作。
#define SWAP(a,b) {\
typeof(a) _t=a;\
a=b;\
b=_t;}
这个宏可以交换所有基本数据类型的变量(整数,字符,结构等)