c++pointersstandardsunspecified-behavior

Is it unspecified behavior to compare pointers to different arrays for equality?


The equality operators have the semantic restrictions of relational operators on pointers:

The == (equal to) and the != (not equal to) operators have the same semantic restrictions, conversions, and result type as the relational operators except for their lower precedence and truth-value result. [C++03 §5.10p2]

And the relational operators have a restriction on comparing pointers:

If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of p<q, p>q, p<=q, and p>=q are unspecified. [§5.9p2]

Is this a semantic restriction which is "inherited" by equality operators?

Specifically, given:

int a[42];
int b[42];

It is clear that (a + 3) < (b + 3) is unspecified, but is (a + 3) == (b + 3) also unspecified?


Solution

  • The semantics for op== and op!= explicitly say that the mapping is except for their truth-value result. So you need to look what is defined for their truth value result. If they say that the result is unspecified, then it is unspecified. If they define specific rules, then it is not. It says in particular

    Two pointers of the same type compare equal if and only if they are both null, both point to the same function, or both represent the same address