Static vs. Dynamic ScopeDynamic ScopeDynamic Scopeldots Dynamic Scope --- ProblemsDynamic Scope --- AdvantagesDynamic Scope --- Advantagesldots Dynamic Scope --- Advantagesldots Readings and References520 —Spring 2008 — 24CSc 520Principles of ProgrammingLanguages24 : Names, Scope, Bindings — Dynamic ScopeChristian [email protected] of Computer ScienceUniversity of ArizonaCopyrightc 2008 Christian Collberg[1]520 —Spring 2008 — 24Static vs. Dynamic ScopePascal is lexically scoped. We can look (textually, or atcompile-time) at a procedure and determine to whichobject an identifier refers.Some languages (Snobol, APL, Perl, some dialects ofLISP) aredynamically scoped. The binding between anidentifier and the object it refers to is not decided untilrun-time.[2]520 —Spring 2008 — 24Dynamic ScopeThe current binding for an identifier is the one last seenduring execution and whose scope has yet to bedestroyed.Consider the example on the next slide.static scope: the program prints1.dynamic scope: the program prints2.Static scope rules match the use of an identifier with theclosest lexically enclosing declaration.Dynamic scope rules choose the most recent activedeclaration at runtime.[3]520 —Spring 2008 — 24Dynamic Scope...var a : integer;procedure first();a := 1;procedure second();var a : integer;first();begina := 2;second();write(a);end[4]520 —Spring 2008 — 24Dynamic Scope — Problemsvar max : integer;procedure scale(x : integer) : real;return x/max;procedure compute(y : integer);var max : integer;write(scale(y));Dynamic scope makes it is easy to accidentally redefinea variable.[5]520 —Spring 2008 — 24Dynamic Scope — Advantagesprocedure A(base : integer)printInt(base, 245);procedure B(base : integer)A();procedure C(base : integer)B();begin C(16); endWe often have to pass around state so that deeplynested procedures can make use of it. DEBUG-flags is acommon example.[6]520 —Spring 2008 — 24Dynamic Scope — Advantages...var base : integer := 10;procedure A()printInt(base, 245);procedure B()A();procedure C()B();beginvar last base := base;base := 16; C();base := last base;endWe can, of course, use global variables.[7]520 —Spring 2008 — 24Dynamic Scope — Advantages...procedure A()printInt(base, 245);procedure B()A();procedure C()B();beginvar base : integer := 16;C();endDynamic scope makes it is easy customize the behaviorof procedures.[8]520 —Spring 2008 — 24Readings and ReferencesRead Scott, pp. 115, 131-135Dynamic Variables, David R. Hanson and Todd A.Proebsting, PLDI
View Full Document