tags:

views:

28

answers:

2

Assuming the language supports these evaluation strategies, what would be the result for call by reference, call by name, and call by value?

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

int i = 3;
int A[5];
A[3] = 4;
swap (i, A[3]);
+1  A: 

call by value -The changes done inside swap method are not visible after calling the method. ie. after swap (i, A[3]);

i, A[3] values don't get changed.

call by ref: The changes done inside swap method are visible after calling the method. ie. after swap (i, A[3]);

i, A[3] values get exchanged.

if you are using C++ as language then the signature of the method should be changed to reflect the pass by reference:

void swap(int& a, int& b)
{
   int temp;
   temp = a;
   a = b;
   b = temp;
}
aJ
So call by value would simple copy the values of i and A[3] into a and b, respectively, swap a with b, and since we simply copied the values it doesn't do anything with them outside of swap's scope because the values are no longer referenced by anything?And because they are still referenced to the objects in call by ref, the swap is done?The pdf I have provided above in response to danben's question shows that in call by name, the incorrect values are swapped... does this happen with call by ref as well?
Boontz
A: 

If you call swap() by value nothing will happen. If you call it by reference it will actually do the swap.

Pass by value when the goal of your function is to return a value.

Pass by reference when you need to update your parameters.

Ben Burnett