What are static scope rules and dynamic scope rules for a variable? Explain difference between them using an example.
Answer:------------
Static Scoping:
Static scoping is also called lexical scoping. In this scoping a
variable always refers to its top level environment. This is a
property of the program text and unrelated to the run time call
stack. Static scoping also makes it much easier to make a modular
code as programmer can figure out the scope just by looking at the
code.
For example, output for the below program is 100, i.e., the
value returned by fun() is not dependent on who is calling it (Like
run() calls it and has a x with value 43). fun() always returns the
value of global variable x.
// A C program to demonstrate static scoping.
#include<stdio.h>
int x = 100;
int fun()
{
return x;
}
int run()
{
int x = 20;
return fun();
}
int main()
{
printf("%d", run());
printf("\n");
return 0;
}
Output :
10
In simpler terms, in static scoping the compiler first searches in the current block, then in the surrounding blocks successively and finally in the global variables.
Dynamic Scoping:
With dynamic scope, a global identifier refers to the identifier
associated with the most recent environment, and is uncommon in
modern languages. In technical terms, this means that each
identifier has a global stack of bindings and the occurrence of a
identifier is searched in the most recent binding.
#include<stdio.h>
int x = 100;
int fun()
{
return x;
}
int run()
{
int x = 20;
return fun();
}
main()
{
printf(run());
}
Output:
20
In simpler terms, in dynamic scoping the compiler first searches the current block and then successively all the calling functions.
Get Answers For Free
Most questions answered within 1 hours.