Re: equality of references
On 10 Mai, 18:23, pauldepst...@att.net wrote:
I understand more about references than it appears. Suppose int& f
(int, int) is a function that returns a reference to a static local
variable. Then f(x,y) == f(a,b) is always true for all integers
x,y,a,b .
No. This is not true for this function:
int& f(int a, int b) {
static int p = 3;
static int q = 4;
if (((p^q) & 1)==0) return p;
return q;
}
int main() {
assert( f(0,0) == f(0,1) ); // fails
}
I'm not clear exactly why although I've seen several
attempts to explain it.
People tried to explain because you don't seem to understand
references. Once a reference has been initialized the reference will
be just another name for the object it refers to. So, if you use the
equality comparison you'll be comparing the values of the aliased
objects and not their addresses. Here are a bunch of other examples:
int main() {
int i = 23;
int j = 23;
int& x = i; // x is an alias for i
int& y = j; // y is an alias for j
assert( x == y); // #1
assert(&x != &y); // #2
assert(&x == &i); // #3
assert(&y == &j); // #4
x = 42;
assert( x != y); // #5
assert(&x != &y); // #2
assert(&x == &i); // #3
assert(&y == &j); // #4
}
1. x and y refer to variables of the same value (23)
2. x and y refer to different variables
3. x refers to i
4. y refers to j
5. x and y refer to variables of different values (23,42)
Cheers!
SG