Call by reference, value, and name

17,165

Solution 1

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

Solution 2

Call by Value : normal way... values of actual parameters are copied to formal parameters.

Call by Reference : instead of the parameters, their addresses are passed and formal parameters are pointing to the actual parameters.

Call by Name : like macros, the whole function definition replaces the function call and formal parameters are just another name for the actual parameters.

Solution 3

By value - there is no changes out the function. all your actions vanish when the function finished.

By reference - your actions indeed changes the variables. By name - I've never heard ...

Passing x+1 is not change, just tells to the function 3 instead 2 or etc...

Share:
17,165
workinMan
Author by

workinMan

Updated on July 22, 2022

Comments

  • workinMan
    workinMan almost 2 years

    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.