Pass-by-value-Result?

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 <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 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.

Tags:

C++