Re: equality of references
On May 10, 7:50 pm, SG <s.gesem...@gmail.com> wrote:
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
Ok. I understand the issues now. Thanks for all who helped on this
thread.
There was a small misunderstanding. When I said
"I'm not clear exactly why although I've seen several
attempts to explain it."
What I actually meant was this: "I'm not sure why f(x,y) == f(a,b) in
the reference-to-static case, though from my reading and from browsing
the web, I've seen several attempted explanations of the reference-to-
static scenario."
In particular, the "several attempts" were not by those on this
newsgroup.
Anyway, all is clear now, and thanks again.
Paul Epstein