Jun 1, 2014 at 4:07pm UTC
Suppose i have a function:
int & f1(int & p) {
return p;
}
void main() {
int a,b;
b = 10;
a = f1(b);
a = 11;
cout<<b<<endl;
}
why when i change a, b doesnt change? a is supposed to be an alias of b right?
please advise?
thanks
Jun 1, 2014 at 5:25pm UTC
Thank you Chervil & Keskiverto.
So, can i say that if it is a structure of a large size, this process is not efficient as it is supposed to be by reference?
In another words, this is as good as an ordinary value return. Hence,
is equivalent as
int f1(int & p);
thanks again.
Jun 1, 2014 at 5:40pm UTC
The function itself is working as intended, it does return by reference. The problem in your original code was in the assignment statement
a = ...
Compare this:
1 2 3 4 5 6 7 8 9 10 11 12 13
int & f1(int & p)
{
return p;
}
int main()
{
int a = 10;
f1(a) = 14;
cout << a << endl;
}
14
Look closely at line 10. Notice the function is to the left of the equals sign, this is possible because the function returns a reference.
Last edited on Jun 1, 2014 at 5:42pm UTC
Jun 1, 2014 at 9:03pm UTC
Thanks, Chervil, i understand.