In almost all implementations, two pointers are equal if and only if their representations are equal, but the standard doesn't guarantee that.
The fact that ptr1 == ptr2
doesn't imply that ptr1
and ptr2
have the same representation. N1570 6.5.9 paragraph 6:
Two pointers compare equal if and only if both are null pointers, both
are pointers to the same object (including a pointer to an object and
a subobject at its beginning) or function, both are pointers to one
past the last element of the same array object, or one is a pointer to
one past the end of one array object and the other is a pointer to the
start of a different array object that happens to immediately follow
the first array object in the address space.
For example, suppose a pointer is represented as a two-part entity, with the first part identifying a segment of memory, and the second part a byte offset within that segment. If two segments can overlap, then there can be two different pointer representations for the same memory address. The two pointers would compare as equal (and the generated code would likely have to do some extra work to make that happen), but if conversion to intptr_t
just copies the representation then (intptr_t)ptr1 != (intptr_t)ptr2
.
(It's also possible that the pointer-to-integer conversion could normalize the representation.)
This possibility is why ==
and !=
are well defined for pointers to different objects, but the relational operators (<
, <=
, >
, >=
) are undefined. The equality operators have to determine whether the two pointers point to the same location, but the relational operators are allowed to compare only the offsets and ignore the base portion (assuming that each object is in a single segment). In practice, almost all modern systems have a monolithic address space, and the equality and relational operators work consistently even though the standard doesn't require them to do so.