edited by
23,730 views
69 votes
69 votes

What will be the output of the following pseudo-code when parameters are passed by reference and dynamic scoping is assumed?                

a = 3;
void n(x) { x = x * a; print (x); }
void m(y) { a = 1 ; a = y - a;  n(a); print (a); }
void main () { m(a); }
  1. $6,2$ 
  2.  $6,6$ 
  3.  $4,2$ 
  4.  $4,4$
edited by

4 Answers

Best answer
138 votes
138 votes

It is a bit confusing as variable declaration is not explicit. But we can see that "$a=3$" and "$a=1$" are declaring new variables, one in global and other in local space.

Main is calling $m(a)$. Since there is no local '$a$', '$a$' here is the global one.

In m, we have "$a = 1$" which declares a local "$a$" and gives $1$ to it. "$a = y-a$" assigns $3-1 = 2$ to '$a$'.

Now, in $n(x)$, '$a$' is used and as per dynamic scoping this '$a$' comes from '$m()$' and not the global one. So, "$x=x*a$" assigns "$2*2 = 4$" to "$x$" and $4$ is printed. Being passed by reference, "$a$" in $m()$ also get updated to $4$. So, D is the answer here.

edited by
4 votes
4 votes

it is D;

Explanation:::

in call by reference value of actual variable can be changed as we have got its address
in Dynamic scoping free variable are resolved from previous function call.

main() is calling m(a); thus a call m(addressof_a) will be made.

now coming m(y),  a's address value will be copied to *y. so now inside m() we have local variable a=1 and y=&a

"a=y-a" will update the local a's value to 2. now m() calls n() by passing address_of_local_variable_a.

coming to n(a),  a's address value will be copied to *x. Now inside n() there is no local variable 'a' is defined/declared. so now it will look for a's value into upper/previous function i.e. m(). since a local variable 'a' is defined into m(). So its value a=2 will be taken. 
note that here x is a pointer pointing to variable 'a' which was declared in m().

now (*x)=(*x)*a will evaluated as 4 which will update the value of 'a' declared in m(). so now coming to print statement address_of_a is passed as argument which will print 4.

after n() calling is over m() will return back to the position where it left and continue just after next statement. which print a's updated value i.e. 4

so finally in output we will have 4,4

edited by
0 votes
0 votes
Answer is B
Answer:

Related questions

35 votes
35 votes
4 answers
3
Sandeep Singh asked Feb 12, 2016
10,022 views
The attribute of three arithmetic operators in some programming language are given below.$$\begin{array}{|c|l|}\hline \textbf{OPERATOR} & \textbf{PRECEDENCE} & \textbf{...
69 votes
69 votes
12 answers
4