Call by reference makes an alias of the formal parameter so every change of typical parameter affects also formal parameter, while pass-by value- result copies the result to the typical parameter and when the function returns, it copies the typical parameter to formal.(Notice that call by value result is completely different to call by value).
Besides the implementation differences between these two parameter passing methods, it seems to me that the final result would be the same.
My question is does these two methods give the same results always or else could you give an example where these two methods return different results?
It would make a difference if the original variable were read during the course of the method. This could happen because:
Here's an example in C#:
using System;
class Test
{
static void Main()
{
int p = 10;
Foo(ref p, () => Console.WriteLine(p));
}
static void Foo(ref int x, Action action)
{
action();
x = 20;
action();
}
}
The output of this is
10
20
... because when action()
is invoked the second time, the value of p
has already changed to 20. If this used pass-by-result, the value of p
would only change when Foo
returned.
See more on this question at Stackoverflow