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.
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function.
Passing by by reference refers to a method of passing the address of an argument in the calling function to a corresponding parameter in the called function. In C, the corresponding parameter in the called function must be declared as a pointer type.
While calling a function, instead of passing the values of variables, we pass address of variables(location of variables) to the function known as “Call By References. In this method, the value of each variable in calling function is copied into corresponding dummy variables of the called function.
When you pass an argument by reference, you pass a pointer to the value in memory. The function operates on the argument. When a function changes the value of an argument passed by reference, the original value changes. When you pass an argument by value, you pass a copy of the value in memory.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With