词汇范围与动态范围

编程入门 行业动态 更新时间:2024-10-28 08:27:22
本文介绍了词汇范围与动态范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我有这个问题,我必须使用两个不同的作用域规则来找出输出.我知道使用词法作用域的输出是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.

更多推荐

词汇范围与动态范围

本文发布于:2023-11-16 07:30:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1602244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词汇   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!