Static vs. Dynamic Scoping
3 May, 2011 § 14 Comments
Have you ever heard of dynamic scoping? Most of us have worked in environments where static scoping is all we have, and probably for good reason.
One of the first things people think about when they hear the words “dynamic scoping” is dynamic memory, which is not at all what dynamic scoping is. Dynamic scoping could also be thought of as context-specific scoping.
C, C++, C#, and JavaScript all use static scoping, whereas Perl and Logo allow dynamic scoping though their local
keyword.
Here’s an example to compare the two:
Static scoping | Dynamic scoping |
---|---|
int b = 5; int foo() { int a = b + 5; return a; } int bar() { int b = 2; return foo(); } int main() { foo(); // returns 10 bar(); // returns 10 return 0; } |
int b = 5; int foo() { int a = b + 5; return a; } int bar() { int b = 2; return foo(); } int main() { foo(); // returns 10 bar(); // returns 7 return 0; } |
Dynamic scoping means that when a symbol is referenced, the compiler/interpreter will walk up the symbol-table stack to find the correct instance of the variable to use. This can be a cool tool to use when writing software, but also a huge source of errors if it is used accidentally.