edited by
8,467 views
25 votes
25 votes

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 by

1 Answer

Best answer
50 votes
50 votes

Correct answer is (D)

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.

edited by
Answer:

Related questions

22 votes
22 votes
3 answers
3