本文介绍了词法范围与动态范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

所以我遇到了这个问题,我必须使用两种不同的范围规则来计算输出.我知道使用词法范围的输出是 a=3b=1,但我很难使用动态范围计算输出.

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.

int a,b;

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

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

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

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

这是我想出来的.使用动态范围,对 ab 的非本地引用可以改变.所以我有 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.

在 main 中,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是全局的,而b是q中的局部.这里全局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 是全局的(值为 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.

这篇关于词法范围与动态范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:13