50 likes | 234 Views
Scope of Variables. Scope. Scope of a variable is the range of statements in which the variable is visible in a program A variable is visible in a statement if the variable name could be used in the location the statement occupies
E N D
Scope • Scope of a variable is the range of statements in which the variable is visible in a program • A variable is visible in a statement if the variable name could be used in the location the statement occupies • Scope rules determine how variable references throughout a program are resolved
Static Scope • COBOL introduced typed variables with global scope • ALGOL 60 popularized the use of static scoping using begin and end to create blocks of code that could be nested
ALGOL 60 Program begin integer x, y; x = 3; printint(x); if (x < 5) begin integer x = 3; printint(x) end; printint(x) end
Dynamic Scoping • Dynamic scoping uses a program call sequence to determine the scope of a variable {int x = 0; Define int foo () { return x; } Define int goo () { int x = 1; return foo(); } goo();} • Calling goo() with static scoping returns 0 • Calling goo() with dynamic scoping returns 1 since a stack is used to maintain the bindings of each variable as a program block is entered