所以我有这个问题,我必须使用两个不同的作用域规则来找出输出.我知道使用词法作用域的输出是a=3和b=1,但是我很难用动态作用域来确定输出. 注意:下面的代码示例使用C语法,但让我们将其视为伪代码.
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(); }这就是我想出的. 使用动态作用域,可以更改对a和b的非本地引用.所以我有a=2(从p()返回),然后是b=4(在q()内部). 所以输出是2 4?
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?
推荐答案我们知道,C没有动态作用域,但假设它具有动态作用域,则程序将输出3 4.
As we know, C doesn't have dynamic scoping, but assuming it did, the program would print 3 4.
总的来说,a和b是全局的.将a设置为2,因为我们将看到p将返回.
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.
在p中(从main调用),b仍然是全局的,但a是p中的局部的.本地a设置为0,但很快就会消失.全局b设置为1.局部p设置为2,并且将返回2.现在全局b是1.
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.
在q中,从main调用,a是全局1,而b是q中的局部1.在这里,全局a设置为3,局部b设置为4.
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.
在打印中,从q调用,a是全局值1(值为3),b是q中的局部值(值为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).
在函数print的最后一步中,我们看到了与静态作用域不同的地方.在静态范围内,a和b将是全局范围.使用动态作用域,我们必须查看调用函数的链,在q中我们找到一个变量b,它将是print中使用的b.
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.
更多推荐
词汇范围与动态范围
发布评论