Lexical scoping vs dynamic scoping

[亡魂溺海] 提交于 2019-12-29 06:25:00

问题


So I have this problem where I have to figure out the output using two different scoping rules. I know the output using lexical scoping is a=3 and b=1, but I am having hard time figure out the output using dynamic scoping.
Note:the code example that follows uses C syntax, but let's just treat it as pseudo-code.

int a,b;

int p() {
    int a, p;
    a = 0; b = 1; p = 2;
    return p;
}

void print() {
    printf("%d\n%d\n",a,b);
}

void q () {
    int b;
    a = 3; b = 4;
    print();
}

main() {
    a = p();
    q();
}

Here is what I come up with. Using Dynamic scoping, the nonlocal references to a and b can change. So I have a=2 ( return from p() ), then b=4 ( inside q() ). So the output is 2 4?


回答1:


As we know, C doesn't have dynamic scoping, but assuming it did, the program would print 3 4.

In main, a and b are the global ones. a will be set to 2, as we will see that this is what p will return.

In p, called from main, b is still the global one, but a is the one local in p. The local a is set to 0, but will soon disappear. The global b is set to 1. The local p is set to 2, and 2 will be returned. Now the global b is 1.

In q, called from main, a is the global one, but b is the one local in q. Here the global a is set to 3, and the local b is set to 4.

In print, called from q, a is the global one (which has the value 3), and b is the one local in q (which has the value 4).

It is in this last step, inside the function print, that we see a difference from static scoping. With static scoping a and b would be the global ones. With dynamic scoping, we have to look at the chain of calling functions, and in q we find a variable b, which will be the b used inside print.




回答2:


C is not a dynamically scoped language. If you want to experiment in order to understand the difference, you're better off with a language like Perl which lets you chose between both.



来源:https://stackoverflow.com/questions/19574605/lexical-scoping-vs-dynamic-scoping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!