NULL是一些标准头中定义的宏对象<stddef.h>.在我的带有GCC 4.8的Debian/Sid/x86-64系统上,它定义如下(第394行和编译器特定/usr/lib/gcc/x86_64-linux-gnu/4.8/include/stddef.h头文件的后面)
/* A null pointer constant. */
#if defined (_STDDEF_H) || defined (__need_NULL)
#undef NULL /* in case <stdio.h> has defined it. */
#ifdef __GNUG__
#define NULL __null
#else /* G++ */
#ifndef __cplusplus
#define NULL ((void *)0)
#else /* C++ */
#define NULL 0
#endif /* C++ */
#endif /* G++ */
#endif /* NULL not defined and <stddef.h> or need NULL. */
#undef __need_NULL
Run Code Online (Sandbox Code Playgroud)
BTW,已经解除引用的指针已知不是空指针值.换句话说,GCC被允许优化(假设p已被声明为int *p;)
int x= *p;
if (!p) do_very_complex_stuff();
// or: if (p == NULL) do_very_complex_stuff();
Run Code Online (Sandbox Code Playgroud)
简单地说
int x= *p;
Run Code Online (Sandbox Code Playgroud)
至少在独立节目之外.
IIRC,优化在Linus Torvalds和一些GCC开发人员之间进行了激烈辩论.
迂腐地,NULL指针(即空指针值)可能不需要是全零位,但我不知道今天有什么实现.