Inspired by this answer about dynamic cast to void*:
... bool eqdc(B* b1, B *b2) { return dynamic_cast<void*>(b1) == dynamic_cast<void*>(b2); } ... int main() { DD *dd = new DD(); D1 *d1 = dynamic_cast<D1*>(dd); D2 *d2 = dynamic_cast<D2*>(dd); ... eqdc(d1, d2) ...
I am wondering if it is fully defined behaviour in C++ (according to the 03 or 11 standard) to compare two void pointers for (in)equality that point to valid, but different objects.
More generally, but possibly not as relevant, is comparing (==or !=) two values of type void* always defined, or is it required that they hold a pointer to a valid object/memory area?
C says:
C++ says:
Hence it would mean that:
a)
So yes, in both C and C++. You can compare them and in this case they shall compare as true iff they point to the same object. That’s simple.
b)
Again, the comparison is well-defined (standard says “if and only if” so every comparison of two pointers is well-defined). But then…
This is surprising!
Indeed that’s not how GCC works:
result:
Maybe it’s UB in C to have a pointer which isn’t a null pointer and doesn’t point to an object, subobject or one past the last object in an array? Hm… This was my guess, but then we have that:
So I can only interpret it that the above program is well-defined and the C standard expects it to print “not equal”, while GCC doesn’t really obey the standard but gives a more intuitive result.