Hi All,
I always get confused between the static and dynamic scoping and hence need someone to examine my evaluation. Following is the example code:
int x = 1;
procedure P(i) {
int x = 1;
i++;
Q(i);
}
procedure Q(j) {
j = j + x;
}
P(x)
print x
In static scoping, we always look at the placement of the function/procedure to understand its scope. Hence,
1 main
is the outermost scope of the program
2 > Procedures P
and Q
are within main and hence they shall always refer to the variables in the main function if not defined in its local scope. This is irrespective of the manner of procedure call
3 > In the example, procedure P
has variable x
defined. Hence it shall shadow the main's x
.
4 > Procedure Q
does not have variable x
defined and hence shall refer to main's x
The output is
1 > For static scoping and pass by value=> 1
2 > For dynamic scoping and pass by value=> 2
3 > For static scoping and pass by reference=> 4
4 > For dynamic scoping and pass by reference=> 3
Please let me know if I have gone wrong somewhere. Also, it will be great if anyone can provide me with useful link on static and dynamic scoping examples such as above.
Thanks,
darkie