Tuesday, 16 August 2016

c++ - Pass-by-value-Result?






Possible Duplicates:
pass by reference or pass by value?
Pass by Reference / Value in C++






Im having trouble with the pass-by-value-result method. i understand pass by reference and pass by value but im not quite clear on pass-by-value result. How similar is it to pass by value(assuming it is similar)?



here is the code



#include 

#include
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 objective is to find out what is the value of "value" and "list" are if you use pass by value result. (NOT pass by value).


Answer



If you're passing by value then you're copying the variable over in the method. Which means any changed made to that variable don't happen to the original variable. This means your output would be as follows:



2   1
1 3
2 5



If you were passing by reference, which is passing the address of your variable (instead of making a copy) then your output would be different and would reflect the calculations made in swap(int a, int b). Have you ran this to check the results?



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



#include 
#include
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 of:




1   2
3 2
2 1


This type of passing is also called Copy-In, Copy-Out. Fortran use to use it. But that is all I found during my searches. Hope this helps.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...