I think you are confusing C++ references with pointers. They are different things! Once a reference is set to reference some object, it can never be changed to refer to another object. And any operation that is performed on the reference is actually done to the value of the referred object. In this case, the assignment y = k
actually sets the value of the object referred to by y to k.
To make things a bit more concrete, I will annotate the example you gave with comments describing what is happening:
void foo(float &y)
{
float k = 0.0;
k += 20.1;
y = k; /* The value of the object referred to by y (i, in this program)
is set to k (20.1f) */
cout << "y = " << y << endl; /* When we write y in this way, we are
really referring to the value of the object referred to by y.
This is why it prints 20.1 instead of some memory address. */
}
int main() {
float i;
foo(i); /* i is passed as a reference to foo */
i+=10.00; /* The value of i was modified in foo. */
cout<<"value of I after returning is :: "<<i<<endl;
return 0;
}
To contrast, here is similar code using pointers instead of references (with a mistake-- it assigns the pointer, y, instead of changing the value pointed at by y):
void foo(float *y)
{
float k = 0.0;
k += 20.1;
y = &k;
cout << "y = " << *y << endl;
}
int main() {
float i = 0;
foo(&i); /* i is passed as a reference to foo */
i+=10.00; /* The value of i was modified in foo. */
cout<<"value of I after returning is :: "<<i<<endl;
return 0;
}
What happens in this case? Well, we print out y = 20.1 and that the value of i after returning is 10.00. In this example, when we assign y = &k
we are changing the variable y, which is local to foo, to refer to k. This has no effect on i (we are not modifying the value pointed to by y), so i is unchanged after we exit foo. If you wanted to change i to equal k after foo, we would have to change the line to read *y = k
.
Hope that cleared up some of the differences between C++ references and pointers! There are plenty of good tutorials out there that do an excellent job explaining the topic.