Download presentation
Presentation is loading. Please wait.
1
Names and Scopes CS 351
2
Program Binding We should be familiar with this notion. A variable is bound to a method or current block e.g in C++: namespace A { class C { void f (bool b) { if (b) { int i = 0; } } }; }
3
Binding Time Compile Time: The compiler chooses how to map the high level code statically. Link Time: Most compilers allows different modules to be compiled independantly. Thus if we include a package or library, the binding of an object does not happen until the linker resolves the external depndencies. Run Time: Binding occurs when we go to run our program. Values associated with variables are bound. Static infers something that happens anytime before the program is executed while dynamic refers to anything from run-time on.
4
Binding Examples static final int MAX = 100; public static void main (String args[]) { String name = args[0]; } if ( a instanceof Integer ) Integer I = (Integer) a;
5
Scope Rules The region in which a binding takes place is known as a Program Scope. We can analyse a C program and determine every binding. When we enter a new block of code, denoted by the curly braces { and }, we can pick out which names refer to which objects. This is known as static scoping. Anything between the { and } is the current scope of local scope. for (int i = 0; i < 10; i++) { … } To avoid variables losing their binding outside of the local scope, we can use the static keyword.
6
Dynamic Scope It is easy to figure out static scope, we can simple look in-side the curly braces. Dynamic Scope is different and depends on the flow of control at runtime and the order of the method calls. The binding of a name is dependant on the most recent execution of that variable so long as it has not been destroyed by leaving it’s scope!!. A compiler cannot tell in advance what the binding will be. Confused?
7
proc main(); int x := 5; proc q(); { x := x + 1;} proc r(); {int x := 0; q(); } { r(); print(x); }. Scoping : Static scoping x -> x output: 6 Dynamic scoping x -> x output: 1
8
Implementing Dynamic Scoping The value of variable x is the last value bound to x. => stack discipline Deep binding Use a global stack for all variables Shallow binding Use a separate stack for each variable Implementing recursion is trivial. First LISP evaluator used dynamic scoping by accident!! Meaning of a call depends on the context.
9
Application of Dynamic Scoping Exception Handling –provide a separate construct in statically scoped language Setting Local Formatting Parameters Input-Output Redirection –avoids passing parameters explicitly through “intermediate” procedures
10
Applications of Dynamic Scope var base = 10;// decimal function print(int n) print n;// decimal. base = 16;// switch to hex print (8);// in hex not decimal base = 10;// back to decimal
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.