Search code examples
pass-by-referencepass-by-valuepass-by-name

Call by reference, value, and name


I'm trying to understand the conceptual difference between call by reference, value, and name.

So I have the following pseudocode:

foo(a, b, c)
{
   b =b++;
   a = a++;
   c = a + b*10
}

X=1;
Y=2;
Z=3;
foo(X, Y+2, Z);

What's X, Y, and Z after the foo call if a, b, and c are all call by reference? if a, b, and c are call-by-value/result? if a, b, and c are call-by-name?

Another scenario:

X=1;
Y=2;
Z=3;
foo(X, Y+2, X);

I'm trying to get a head start on studying for an upcoming final and this seemed like a good review problem to go over. Pass-by-name is definitely the most foreign to me.


Solution

  • When you pass a parameter by value, it just copies the value within the function parameter and whatever is done with that variable within the function doesn't reflect the original variable e.g.

    foo(a, b, c)
    {
       b =b++;
       a = a++;
       c = a + b*10
    }
    
    X=1;
    Y=2;
    Z=3;
    foo(X, Y+2, Z);
    //printing will print the unchanged values because variables were sent by value so any //changes made to the variables in foo doesn't affect the original.
    print X; //prints 1
    print Y; //prints 2
    print Z; //prints 3
    

    but when we send the parameters by reference, it copies the address of the variable which means whatever we do with the variables within the function, is actually done at the original memory location e.g.

    foo(a, b, c)
    {
       b =b++;
       a = a++;
       c = a + b*10
    }
    
    X=1;
    Y=2;
    Z=3;
    foo(X, Y+2, Z);
    
    print X; //prints 2
    print Y; //prints 5
    print Z; //prints 52
    

    for the pass by name; Pass-by-name