Scope and Environment
- Static Scope: determined by the location in code
- Dynamic Scope: determined by the call stack
int x; // global
void funD() { print(x); }
void funC(int x) { print(x); funD(); }
void funB() { print(x); funC(2); }
void funA() { int x; x = 5; print(x); funB(); }
void main() { x = 3; funA(); }
What prints? |
Static Scope |
Dynamic Scope |
It prints |
5323 |
5522 |
in funA |
5 (local) |
5 (local) |
in funB |
3 (global) |
5 (it's 5 in A and still in scope) |
in funC |
2 (parameter) |
2 (parameter) |
in funD |
3 (global) |
2 (it's 2 in C and still in scope) |
Scope and Environment
int x; // global
void funF() { print(x); }
void funE() { funF(); }
void funD() { funE(); }
void funC(int x) { funD(); funE(); }
void funB() { funC(2); funE(); }
void funA() { int x; x = 5; funB(); funE(); }
void main() { x = 3; funA(); funE(); }
What prints? |
Static Scope |
Dynamic Scope |
It prints |
33333 |
22553 |
A->B->C->D->E->F |
3 (global in F) |
2 (it's 2 in C and still in scope) |
A->B->C->E->F |
3 (global in F) |
2 (it's 2 in C and still in scope) |
A->B->E->F |
3 (global in F) |
5 (it's 5 in A and still in scope) |
A->E->F |
3 (global in F) |
5 (it's 5 in A and still in scope) |
E->F |
3 (global in F) |
3 (it's 3 in main and still in scope) |