最近开始研读Nginx的源代码,首先就遇到如下的代码:
typedef intptr_t ngx_int_t;
typedef uintptr_t ngx_uint_t;
intptr_t和uintptr_t是什么类型?以前没见过,于是查了一下。
这两个数据类型是ISO C99定义的,具体代码在linux平台的/usr/include/stdint.h头文件中。
该头文件中定义intptr_t和uintptr_t这两个数据类型的代码片段如下:
/* Types for `void *' pointers. */
#if __WORDSIZE == 64
# ifndef __intptr_t_defined
typedef long int intptr_t;
# define __intptr_t_defined
# endif
typedef unsigned long int uintptr_t;
#else
# ifndef __intptr_t_defined
typedef int intptr_t;
# define __intptr_t_defined
# endif
typedef unsigned int uintptr_t;
#endif
在64位的机器上,intptr_t和uintptr_t分别是long int、unsigned long int的别名;在32位的机器上,intptr_t和uintptr_t分别是int、unsigned int的别名。
那么为什么要用typedef定义新的别名呢?我想主要是为了提高程序的可移植性(在32位和64位的机器上)。很明显,上述代码会根据宿主机器的位数为intptr_t和uintptr_t适配相应的数据类型。
另外,如注释所言,定义这两个数据类型别名也是为了“void *”指针。
在C语言中,任何类型的指针都可以转换为void *类型,并且在将它转换回原来的类型时不会丢失信息。