Evaluation of variable through Pass By Name

92 views Asked by At

I have a doubt regarding Pass By Name

   Procedure test ( int c, int d) 
    { 
      int k = 10;

      c = 5;

      d = d + 2 ;

      k = c + d;

      print (k);
}

main()
{
    k = 1;

    test(k,k);

    print (k);
}

I did refer to one of the earlier question on what is pass by name and how does it work

and the link given in it :

Pass by name parameter passing

The Question i have is : will the above code print : ( 14 , 1 ) or (14, 14)

Basically doubt is whether the value of k in procedure be reflected in main procedure or not.

I'm preparing for an exam. This's a code snippet given in one of the question bank.

1

There are 1 answers

1
ibid On

Pass by name, when you are passing a variable and not a more complex expression, behaves the same as pass by reference. Thus, your code prints 14 and 7.

Note that the local variable k in your procedure test is not the same variable as the global variable k. In test, the assignments c = 5 and d = d + 2 both assign to the global k, as it was passed by name to test through both c and d. Thus, after these assignments, the global k has the value 7. The assignment k = c + d; affects the local variable k (as that is the k in scope at that time), not the global variable k (which is shadowed by the local variable), and thus the global k retains the value 7 after the assignment.