Search code examples
pass-by-referencepass-by-value

Understanding Pass-By-Value-Result


Consider the following program

int i;
int a[2];
void foo(int x, int y)
{
    x++;
    i++;
    y++;
}

main()
{
    a[0] = 1;
    a[1] = 1;
    i = 0;
    foo(a[i], a[i]);
    print(a[0]);
    print(a[1]);
}

I'm trying very hard to understand pass-by-value-result. However couldn't get the hang of it. I know it's similar to pass-by-reference. But in what way? How does the results differ in the above case? When does it actually use the "reference" of the values?


Solution

  • Results are:

    2

    1

    This is because, in pass-by-value-result, any modification done to the variables within the calling function, will not be updated until the function exits.

    With the same program, using pass-by-reference,

    3

    1

    would be printed, because it references to the same address and updates any modification done immediately.