开发者

Static and dynamic scoping

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 scop开发者_开发问答e. 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


There's a number of articles out there. Google is your friend :-)

[Edit] After reading through some of those links I think the following is true:

  1. For static scoping and pass by value=> 1
  2. For dynamic scoping and pass by value=> 1
  3. For static scoping and pass by reference=> 4
  4. For dynamic scoping and pass by reference=> 3

Point 2 should return 1 because you're passing by value so the x you're passing in never gets modified.

Tim Hoolihan has an example which is easier to follow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜