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.
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
kin your proceduretestis not the same variable as the global variablek. Intest, the assignmentsc = 5andd = d + 2both assign to the globalk, as it was passed by name totestthrough bothcandd. Thus, after these assignments, the globalkhas the value7. The assignmentk = c + d;affects the local variablek(as that is thekin scope at that time), not the global variablek(which is shadowed by the local variable), and thus the globalkretains the value7after the assignment.