什么是词汇范围? [英] What is lexical scope?

查看:192
本文介绍了什么是词汇范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以给我一个关于词法范围的简要介绍吗?

Could someone please give me a brief introduction to lexical scoping?

推荐答案

我通过例子理解它们。 :)

I understand them through examples. :)

首先,词汇范围(也称为静态范围),采用类C语法:

First, Lexical Scope (also called Static Scope), in C-like syntax:

void fun()
{
    int x = 5;

    void fun2()
    {
        printf("%d", x);
    }
}

每个内层都可以访问其外层。

Every inner level can access its outer levels.

还有另一种方法,叫做动态范围,首先实现Lisp,
再次使用C语法语法:

There is another way, called Dynamic Scope used by first implementation of Lisp, again in C-like Syntax:

void fun()
{
    printf("%d", x);
}

void dummy1()
{
    int x = 5;

    fun();
}

void dummy2()
{
    int x = 10;

    fun();
}

这里有趣可以在 dummy1 dummy2 或任何<中访问 x code> x 在任何调用 fun 的函数中,其中声明了 x

Here fun can either access x in dummy1 or dummy2, or any x in any function that call fun with x declared in it.

dummy1();

将打印5,

dummy2();

将打印10。

第一个一个被称为静态,因为它可以在编译时推断,第二个被称为动态,因为外部范围是动态的,并且取决于函数的链调用。

The first one is called static because it can be deduced at compile-time, the second is called dynamic because the outer scope is dynamic and depends on the chain call of the functions.

我发现静态范围对于眼睛更容易。大多数语言最终都是这样,甚至Lisp(可以做到这两种,对吗?)。动态范围就像将所有变量的引用传递给被调用函数。

I find static scoping easier for the eye. Most languages went this way eventually even Lisp(can do both, right?). Dynamic scoping is like passing references of all variables to the called function.

编译器无法推导出函数外部动态范围的一个示例,请考虑我们的上一个示例,如果我们写这样的东西:

An example of why the compiler can not deduce the outer dynamic scope of a function, consider our last example, if we write something like this:

if(/* some condition */)
    dummy1();
else
    dummy2();

调用链取决于运行时条件。如果是,则调用链如下所示:

The call chain depends on a run time condition. If it is true, then the call chain looks like:

dummy1 --> fun()

如果条件为假:

dummy2 --> fun()

fun的外部范围在这两种情况下都是调用者加上调用者的调用者等等

The outer scope of fun in both cases is the caller plus the caller of the caller and so on.

提到C语言不允许嵌套函数也不动态范围。

Just to mention that C language does not allow nested functions nor dynamic scoping.

这篇关于什么是词汇范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆