Search code examples
oopparadigmsdynamic-scope

What is the output when you use shallow binding?


x : integer := 3                //global scope
y : integer := 4                //global scope
procedure add
    x := x + y
procedure second(P : procedure)
    x : integer := 5
    P()
procedure first
    y : integer := 6
    second(add)
first()               //first procedure call in the main function
write integer(x)      //function to print the value of a variable

After first() is run, add() modifies second::x, not ::x right? So the output is 3... but the answer given is: Dynamic Scope (shallow binding): (x=5+y=6)=11


Solution

  • The semantics of your fictitious language is somewhat vague and I am forced to make assumptions, for instance a statement such as ...

        x : integer := 5
    

    ... in function second is defining a new local variable x initialized to 5 rather than assigning a new value to global variable x.

    Then with shallow binding by time add is called function second will have set local variable x to 5 and function first will have set local variable y to 6. Therefore add will compute a new value of x as 11. This I think we all agree on.

    But I would interpret function add as updating the local variable x of function second, not the global x variable, leaving the global variable x unmodified. Therefore 3 should be printed.