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

Pass-by-value vs pass-by-reference vs pass-by-value-result


I've got this question, and I'm a bit confused as to what would be printed, especially for pass-by-reference. What value would be passed to x if there are two parameters? Thanks!

Consider the following program. For each of the following parameter-passing methods, what is printed?

a. Passed by value

b. Passed by reference

c. Passed by value-result

void main()
{
    int x = 5;
    foo (x,x);
    print (x);      
}

void foo (int a, int b)
{
    a = 2 * b + 1;
    b = a - 1;      
    a = 3 * a - b;
}

Solution

  • The first two should be pretty straightforward, the last one is probably throwing you because it's not really a C++ supported construct. It's something that had been seen in Fortran and Ada some time ago. See this post for more info

    As for your results, I think this is what you would get:

    1)

    5
    

    2)

    x = 5,
    a = 2 * 5 + 1 = 11
    b = 11 - 1 = 10
    a = 3 * 10 - 10 = 20;  // remember, a and b are the same reference!
    x = 20
    

    3) Consider this (in C++ style). We will copy x into a variable, pass that by reference, and then copy the result back to x:

    void main()
    {
        int x = 5;
        int copy = x;
        foo (copy,copy);  // copy is passed by reference here, for sake of argument
        x = copy;
        print (x);      
    }
    

    Since nothing in the foo function is doing anything with x directly, your result will be the same as in #2.

    Now, if we had something like this for foo

    void foo (int a, int b)
    {
        a = 2 * b + 1;
        x = a - 1;      // we'll assume x is globally accessible
        a = 3 * a - b;
    }
    

    Then # 2 would produce the same result, but #3 would come out like so:

    a = 2 * 5 + 1 = 11
    x = 11 - 1 = 10  // this no longer has any effect on the final result
    a = 3 * 11 - 11 = 22
    x = 22