Consider the following pseudocode: x : integer := 1 y : integer := 2 procedure…

2013

Consider the following pseudocode:

 x : integer := 1
 y : integer := 2
 procedure add
 x := x + y

 procedure second (P: procedure)
 x : integer := 2
 P()
 procedure first
 y : integer := 3
 second(add)
 first()
 write_integer (x)

What does it print if the language uses dynamic scoping with deepbinding?

  1. A.

    2

  2. B.

    3

  3. C.

    4

  4. D.

    5

Attempted by 78 students.

Show answer & explanation

Correct answer: C

Step-by-step Execution:

Initial global variables:
x = 1
y = 2

Procedure add:
x := x + y

This procedure adds y into x.

Procedure second(P):
x : integer := 2
P()

Here, second creates a local x = 2 and then calls procedure P.

Procedure first:
y : integer := 3
second(add)

Inside first, a local y = 3 is created and add is passed to second.

Important Concept:
The language uses dynamic scoping with deep binding.

In deep binding, when add is passed as a parameter in:
second(add)

the current referencing environment is saved.

At this moment:

  • global x = 1

  • local y inside first = 3

Now execution enters second:
x : integer := 2

This x is local to second.

Then:
P()

means add() is executed.

Inside add:
x := x + y

Using deep binding:

  • x refers to global x = 1

  • y refers to y from first = 3

So:
x = 1 + 3 = 4

Global x becomes 4.

Finally:
write_integer(x)

prints global x.

Output:
4

Explore the full course: Isro