Note that in both cases your undefined behavior can be defined if the set of valid pointers is contiguous and can be represented by the integers. In that case, the return value of ptr2 - ptr1 is the difference between the two integer representations, and ptr1 < ptr2 is true when ptr1 has a smaller integer representation than ptr2, and false otherwise.
So undefined behavior is not necessarily to be avoided. It needs to be evaluated on a platform-by-platform basis. It's not defined in the standard, because the standard is describing an abstract "computer" which supports the operations. However in the real world, with concrete computers such as x86 or ARM pointers have an integer representation and arithmetic and logical tests can reasonably expected to work, even if they have no standard definition in the abstract "C machine."
And it's tremendously unfair and probably a bug for any "optimizing compiler" to use that undefined behavior to do anything other than subtract the two pointers and return true or false when they're logically compared.
It might be true on X86 if you’re using a flat memory layout. With segmented memory or PAE, all bets are off. Thankfully PAE is usually the responsibility of the operating system which provides a flat address space to each process.
> And it's tremendously unfair and probably a bug for any "optimizing compiler" to use that undefined behavior to do anything other than subtract the two pointers and return true or false when they're logically compared.
So undefined behavior is not necessarily to be avoided. It needs to be evaluated on a platform-by-platform basis. It's not defined in the standard, because the standard is describing an abstract "computer" which supports the operations. However in the real world, with concrete computers such as x86 or ARM pointers have an integer representation and arithmetic and logical tests can reasonably expected to work, even if they have no standard definition in the abstract "C machine."
And it's tremendously unfair and probably a bug for any "optimizing compiler" to use that undefined behavior to do anything other than subtract the two pointers and return true or false when they're logically compared.