1

C99 6.3.2.3/3 值为 0 的整型常量表达式或转换为 void * 类型的此类表达式称为空指针常量。55) 如果将空指针常量转换为指针类型,则生成的指针,称为空指针,保证比较不等于指向任何对象或函数的指针。

它是否说两个空指针不比较相等?但他们这样做:

int *a = 0;
int *b = 0;

assert(a == b); // true

我想知道在这种情况下什么是不平等的?

4

2 回答 2

3

您需要仔细阅读标准:空指针比较不等于任何指向对象函数的指针。不能通过对对象(例如&foo)使用地址运算符来生成空指针。任何函数指针都保证为非 NULL。将这两者结合起来意味着空指针永远不会与 ptr-to-object 或 ptr-to-function 进行比较。

澄清一下,比较不平等的意思a == b是假的(等同于a != b真)。

您引用的段落没有说明比较两个空指针,但下一段确实:

将空指针转换为另一种指针类型会产生该类型的空指针。任何两个空指针应该比较相等。

比较相等表示为a == b真(相同a != b为假)。

于 2012-12-03T13:17:27.850 回答
1

如果对声明的解释有误,请纠正我。

int main() {
   void* a = (void *)0;
   int* b;    // pointer b is of different type to a
   printf((a == b) ? "equal" : "not equal");
   return 0;
}

结果:

not equal

该声明,

If a null pointer constant is converted to a pointer type, the resulting pointer, called a null
pointer, is guaranteed to compare unequal to a pointer to any object or function.

说,当且仅当两者都是空指针或相同对象或函数的指针并且在比较两种不同的指针类型时不相等时,这两个指针才能比较相等。

于 2012-12-03T13:05:52.857 回答