why return reference doesn't alter the other variable

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
a is supposed to be an alias of b right?
No. The return value of the function is an alias of b.

Thus
 
    a = f1(b);
has the same effect as
 
    a = b;


If you wanted a to be an alias of b, you could put
 
    int &a = b;
or
 
    int &a =  f1(b);
a is supposed to be an alias of b right?

Wrong. You have:
1
2
int a;
int b;

Two independent variables.

It is true that f1() returns a reference, but the assignment operator copies data from the referred to variable rather than turning a variable into reference..
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.
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
Thanks, Chervil, i understand.
Topic archived. No new replies allowed.