Search code examples
pseudocodedynamic-scope

What is the output of this (C-like) pseudo-code using dynamic scoping?


What will be the output of the given pseudo-code using DYNAMIC SCOPING ? Here I want to know what will be the values of x that will be printed.

It is just simple pseudo code in a language that resembles C but has dynamic scoping.

    integer x,y;

    p(integer n){
        x=(n+2)/(n-3);
    }

    q(){
        integer x,y;
        x=3;
        y=4;
        p(y);
        write(x);
    }

    main(){
        x=7;
        y=8;
        q();
        write(x);
    }

Solution

  • With dynamic scope, each identifier has a global stack of bindings. Introducing a local variable with name x pushes a binding onto the global x stack (which may have been empty), which is popped off when the control flow leaves the scope. Evaluating x in any context always yields the top binding. In other words, a global identifier refers to the identifier associated with the most recent environment. Note that this cannot be done at compile time because the binding stack only exists at runtime, which is why this type of scoping is called dynamic scoping. http://en.wikipedia.org/wiki/Scope_(computer_science)

    Having read this theory.. if I answer this question using dynamic scoping First when main() is called x=7 and y=8 are pushed in stack then when q() is called it pushes x=3 and y=4 ; now p(n) doesn't have x declared so it will use the last invocation of x as declaration which is in q() and will update its value to '6'.

    then when scope of q() will end its values will be popped out of stack and globally invoked values of x=7 and x=8 will remain there so x=7 will be printed.

    ANS : 6 and 7 are printed