Reputation: 41
I'm reading a C++ textbook and I encounter the following practice exercise.
True or false? Explain:
A. If (x == y) then (&x == &y).
B. If (x == y) then (*x == *y).
The textbook says the A is true and B is false but I believe it should be the reverse? Just because x == y doesn't mean that &x and &y have the same address and I don't see why B is false.
Upvotes: 0
Views: 181
Reputation: 238281
Firstly, I interpret the question such that the proposition must be true for any type for which the expressions are well formed.
A. is clearly false, because two objects can have the same value, but can not be stored in the same address. But it isn't false for all cases. For example, when one is a reference to the other.
B. is also false, but less clearly. If the equals and/or the dereference operators have been overloaded with convoluted functionality, then the proposition isn't guaranteed to hold. But for simple pointers to fundamental types, the proposition is true.
So, if we ignore the possibility of non-fundamental types, the book's answers do indeed seem to be reversed. Considering overloading, B appears to be correct perhaps by accident, and A simply wrong.
Upvotes: 1
Reputation:
A is false. The statement &x == &y
is the same as saying 0x001F == 0x001E
which is false.
B however is true. Dereferencing the pointer by *x
is literally comparing the values stored at those addresses. Hope this helps.
Upvotes: 2