Pass-by-value result?

Possible duplicates:
pass by reference or pass by value?
Passing by reference / value in C ++

I'm having problems with the pass-by-value-result method. I understand that I am passing by reference and passing by value, but I do not quite understand the result of passing by value. How does this look like a pass by value (assuming it looks like)?

here is the code

#include <iostream> #include <string.h> using namespace std; void swap(int a, int b) { int temp; temp = a; a = b; b = temp; } int main() { int value = 2; int list[5] = {1, 3, 5, 7, 9}; swap(value, list[0]); cout << value << " " << list[0] << endl; swap(list[0], list[1]); cout << list[0] << " " << list[1] << endl; swap(value, list[value]); cout << value << " " << list[value] << endl; } 

Now the task is to find out what the value "value" and "list" are, if you use the result of passing by value. (DOES NOT pass by value).

+6
source share
2 answers

If you pass by value, you copy the variable in the method. This means that any changes made to this variable do not match the original variable. This means that your result will be as follows:

 2 1 1 3 2 5 

If you followed a link that passes the address of your variable (instead of creating a copy), then your result will be different and will reflect the calculations performed in swap (int a, int b). Did you run this to check the results?

EDIT After some research, I found a few things. C ++ Does not support Pass-by-value-result, however it can be modeled. To do this, you create a copy of the variables, pass them by reference to your function, and then set the initial values ​​to temporary values. See code below ..

 #include <iostream> #include <string.h> using namespace std; void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; } int main() { int value = 2; int list[5] = {1, 3, 5, 7, 9}; int temp1 = value; int temp2 = list[0] swap(temp1, temp2); value = temp1; list[0] = temp2; cout << value << " " << list[0] << endl; temp1 = list[0]; temp2 = list[1]; swap(list[0], list[1]); list[0] = temp1; list[1] = temp2; cout << list[0] << " " << list[1] << endl; temp1 = value; temp2 = list[value]; swap(value, list[value]); value = temp1; list[value] = temp2; cout << value << " " << list[value] << endl; } 

This will give you the results:

 1 2 3 2 2 1 

This type of transfer is also called Copy-In, Copy-Out. Fortran uses it. But that’s all I found during my searches. Hope this helps.

+7
source

Use links as your parameters, for example:

 void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; } 

a and b will now have the actual value.

0
source

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


All Articles