References as function arguments?

I have problems with links. Consider this code:

void pseudo_increase(int a){a++;} int main(){ int a = 0; //.. pseudo_increase(a); //.. } 

Here the value of the variable a does not increase, since the clone or its copy is transferred, and not the variable itself.
Now consider another example:

 void true_increase(int& a){a++;} int main(){ int a = 0; //.. true_increase(a); //.. } 

It says that the value of a will increase, but why?

When true_increase(a) is called, a copy of a will be passed. This will be another variable. Consequently, &a will be different from the true address of a . So how does the value of a increase?

Correct me where I am wrong.

+6
source share
3 answers

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 as an alias for a . Everything you assign to b will also be assigned to a (because b is a reference to a ). Passing a parameter by reference 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; } 
+6
source

When true_increase (a) is called, a copy of 'a' will be passed

What are you mistaken. Reference will be made to a . This is what & is next to the type of parameter. Any operation that occurs with reference is applied to the referent.

+5
source

in your function true_increase (int and a), what gets the code inside is not COPYING the integer value you specified. this is a reference to the same memory location in which your integer value is in the computer's memory. Therefore, any changes made through this link will occur with the actual integer that you originally announced, and not with a copy of it. Therefore, when the function returns, any change you made to the variable through the link 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 already mentioned, a copy of the original variable is used, and therefore everything that you did inside the function is not reflected in the original variable.

+1
source

Source: https://habr.com/ru/post/906367/


All Articles