1
votes

C99 6.3.2.3/3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.55) 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.

Does it says that two null pointers don't compare equal? But they do:

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

assert(a == b); // true

I wonder what is unequal in this case?

2

2 Answers

3
votes

You need to read the Standard carefully: A null-pointer compares unequal to any pointer to an object or function. A null-pointer cannot be generated by using the address-of operator on an object (e.g. &foo). Any function pointer is guaranteed to be non-NULL. Taken together these two imply that a null-pointer never compares equal to a ptr-to-object or ptr-to-function.

To clarify, to compare unequal means that a == b is false (identical with a != b is true).

The paragraph you cited does not say anything about comparing two null-pointers, but the next paragraph does:

Conversion of a null pointer to another pointer type yields a null pointer of that type. Any two null pointers shall compare equal.

To compare equal means that a == b is true (identical with a != b is false).

1
votes

Please correct me if am wrong in interpreting the statement.

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

Result:

not equal

The statement,

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.

says, the two pointers can be compared equal if and only if both are null pointers or pointers of same object or function and unequal when you compare two different pointer types.