Frage

I get confused when dealing with the static scope and dynamic scope, and for this pseudocode I have to find both. For both I believe it should print out: 9 4 2 3 however, I'm not entirely sure. Any help would be appreciated, thanks.

g: integer

procedure B(a: integer)
    x: integer

    x := a X a
    R(1)

procedure A(n: integer)
    g := n

procedure R(m: integer)
    write_integer(x)
    x /:= 2       -- integer division
    if x > 1
        R(m + 1)
    else
        A(m)

procedure main()  -- entry point
    B(3)
    write_integer(g)
War es hilfreich?

Lösung

If your language were statically scoped, then the variable x would be local only to the function B, and it would not be visible outside B.

However, your language is dynamically scoped: The first time the control flow passes over the line x: integer, the variable x is now globally accessible.

So, here's the order of events:

  • B(3) assigns x := 9

  • R(1) writes 9 and assigns x = 4 and calls R(2)

  • R(2) writes 4 and assigns x = 2 and calls R(3)

  • R(3) writes 2 and assignx x = 1 and calls A(3)

  • A(3) assigns g = 3

  • write_integer(g) prints 3.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top