Static and dynamic scoping

1,431 views 6 slides Nov 30, 2019
Slide 1
Slide 1 of 6
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6

About This Presentation

This presentation is all about Static and Dynamic rule used in the programming , It is important to understand the scope of variable and how program is processed inside the memory.
I hope this (.ppt) will be helpful to students studying Computer Science :)


Slide Content

Static and Dynamic Scoping - presentation by Nusrat.Mohammed.Hanif

What is Scoping ? Scoping refers to the visibility of variables . In simple words , we can say a textual region of program in which binding is active is its scope. A scope is the body of module class , subroutine or structured control flow statement sometimes called as block .

Types of Scopes: There are 2 types of scopes : 1.Static Scoping 2. Dynamic Scoping Static Scoping : it is also called as lexical scoping. It is binding between names and object can be determined at compile time. In static scoping the compiler checks for say variable “x” if it is present in local block if it is not there then it search in the main or parent block. Dynamic Scoping : It is binding between names and object can be determined at run time. In dynamic scoping the compiler checks for say variable “x” if it is present in local block if it is not there then it search in the sibling functions block or from where it is called.

Example : 1 int x ; i nt main() { x=2; f(); g(); } V oid f() { int x=3; h(); } void g() { int x=4; h() void h() { printf (“%d\”,x); } Output : By static rule : x=2  main’s x x=2  main’s x By dynamic rule : x=3  f()’s x x=4  g()’s x

Example : 2 Begin integer m , n; Procedure hardy : begin print(“in hardy n =“ , n); end; Procedure laurel( n:int ) : begin print(“in laurel m =“ , m); print(“in laurel n =“ , n); hardy; end; // m=50 ; n=100; print(in main prog n =“ ,n ); laurel(1); hardy; end; Output : By static rule : n=100  main’s n m=50  main’s m n=1  laurel’s n n=100  main’s n n=100  main’s n By dynamic rule (sibling) n=100  main’s n m=50  main’s m n=1  laurel’s n n=1  (hardy)laurel ’s n n=100  main’s n

Example : 3 int b=5; int foo() { int a=b+5; return a; } int bar() { int b=2; return foo() ; } int main() { foo(); bar(); return 0; } Output : By static rule : foo=10 (foo‘s return a) bar =10 (foo’s return a) By dynamic rule : foo=10 (foo‘s return a) bar =7 (bar‘s return foo)