1.8k views

Consider the program below in a hypothetical language which allows global variable and a choice of call by reference or call by value methods of parameter passing.

int i ;
program main ()
{
int j = 60;
i = 50;
call f (i, j);
print i, j;
}
procedure f (x, y)
{
i = 100;
x = 10;
y = y + i ;
}

Which one of the following options represents the correct output of the program for the two parameter passing mechanisms?

1. Call by value : $i = 70, j = 10$; Call by reference :$i = 60, j = 70$
2. Call by value : $i = 50, j = 60$; Call by reference :$i = 50, j = 70$
3. Call by value : $i = 10, j = 70$; Call by reference :$i = 100, j = 60$
4. Call by value : $i = 100, j = 60$; Call by reference :$i = 10, j = 70$

edited | 1.8k views
+3
Why is this marked out of syllabus?
+10

CALL BY VALUE :- $i$ as global variable declared. Then in $main()$ a local variable $j$ as integer declared i.e $j=60$ And global variable $i$ initialized to $50$ by $i=50$. Now procedure $f$ called and values of $i$ and $j$ are passed to it. i.e., in $f(i,j) \rightarrow f(x, y)$ content of memory location of $i$ (here $50$) is copied to memory location of $x$ (which is different from $i$) and content of memory location of $j$ (here, $60$) is copied to memory location of $y$. Then in $f(x,y)$ $i=100$ changes the global $i$ to $100$,  $X= 10$ changes the local $X$ from $50$ to $10$ and $Y= y+ i$ means $y=60+100=160$. Now when return back to main, $i$ and $j$ will be $100$ and $60$ respectively.

CALL BY REFERENCE:- Now procedure $f$ called and passed reference of $i$ and $j$ to it. i.e., in $f(i,j) \rightarrow f(x, y)$ $x$ and $y$ are new names (aliases) pointing to the same memory location of $i$ and $j$ respectively. So, $i = 100$ changes the global $i$ to $100$ and $x= 10$ means $x$ as well as global $i =10$ (as the $i$ being passed is the global variable and $x$ and $i$ share the same address).
$y= y+ i$ means $y = 60+10=70$ and this changes the value of $j$ also to $70$ as $j$ and $y$ have the same address. Now when return back to main, $i$ and $j$ will be $10$ and $70$ respectively.

by Active (3.3k points)
edited by
+2

Call by value: "Passed copies" not "passed reference". Let address of i be 1000, and that of j be 2000. Then in f(x,y), address of X will be some 3000 and address of Y will be another. Just that the content of address 1000 is copied to address of X and content of Y is copied to address of Z. And that is why it is called "Call-by-value"
+1
Sorry for typo mistake. ..corrected it now
0
@Arjun sir please explain call by referrence too.
0
Beautifully explained.