Reputation: 1506
I have a trouble with references. Consider this code:
void pseudo_increase(int a){a++;}
int main(){
int a = 0;
//..
pseudo_increase(a);
//..
}
Here, the value of variable a
will not increase as a clone or copy of it is passed and not variable itself.
Now let us consider an another example:
void true_increase(int& a){a++;}
int main(){
int a = 0;
//..
true_increase(a);
//..
}
Here it is said value of a
will increase - but why?
When true_increase(a)
is called, a copy of a
will be passed. It will be a different variable. Hence &a
will be different from true address of a
. So how is the value of a
increased?
Correct me where I am wrong.
Upvotes: 6
Views: 257
Reputation: 18177
Consider the following example:
int a = 1;
int &b = a;
b = 2; // this will set a to 2
printf("a = %d\n", a); //output: a = 2
Here b
can be treated like an alias for a
. Whatever you assign to b
, will be assigned to a
as well (because b
is a reference to a
). Passing a parameter by reference
is no different:
void foo(int &b)
{
b = 2;
}
int main()
{
int a = 1;
foo(a);
printf("a = %d\n", a); //output: a = 2
return 0;
}
Upvotes: 6
Reputation: 2419
in your true_increase(int & a) function, what the code inside is getting is NOT A COPY of the integer value that you have specified. it is a reference to the very same memory location in which your integer value is residing in computer memory. Therefore, any changes done through that reference will happen to the actual integer you originally declared, not to a copy of it. Hence, when the function returns, any change that you did to the variable via the reference will be reflected in the original variable itself. This is the concept of passing values by reference in C++.
In the first case, as you have mentioned, a copy of the original variable is used and therefore whatever you did inside the function is not reflected in the original variable.
Upvotes: 1
Reputation: 103761
When true_increase(a) is called , copy of 'a' will be passed
That's where you're wrong. A reference to a
will be made. That's what the &
is for next to the parameter type. Any operation that happens to a reference is applied to the referent.
Upvotes: 5