I understand them through examples.
(我通过示例了解它们。)
:)(:))
First, Lexical Scope (also called Static Scope), in C-like syntax:
(首先,采用类似C的语法的词法作用域(也称为静态作用域):)
void fun()
{
int x = 5;
void fun2()
{
printf("%d", x);
}
}
Every inner level can access its outer levels.
(每个内部级别都可以访问其外部级别。)
There is another way, called Dynamic Scope used by first implementation of Lisp, again in C-like Syntax:
(同样,在类似C的语法中,Lisp的第一个实现使用了另一种称为动态范围的方法:)
void fun()
{
printf("%d", x);
}
void dummy1()
{
int x = 5;
fun();
}
void dummy2()
{
int x = 10;
fun();
}
Here fun
can either access x
in dummy1
or dummy2
, or any x
in any function that call fun
with x
declared in it.
(这里fun
既可以访问x
在dummy1
或dummy2
,或x
任何函数调用fun
与x
在其声明。)
dummy1();
will print 5,
(将打印5)
dummy2();
will print 10.
(将打印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.
(第一个称为静态,因为它可以在编译时推导,第二个称为动态,因为外部范围是动态的,并且取决于函数的链调用。)
I find static scoping easier for the eye.
(我发现静态范围界定对眼睛来说更容易。)
Most languages went this way eventually even Lisp(can do both, right?).(最终,大多数语言甚至都使用Lisp(可以同时做,对吗?)。)
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:(如果为true,则调用链如下所示:)
dummy1 --> fun()
If the condition is false:
(如果条件为假:)
dummy2 --> fun()
The outer scope of fun
in both cases is the caller plus the caller of the caller and so on .
(在这两种情况下, fun
的外部范围是调用者加上调用者的调用者,依此类推 。)
Just to mention that C language does not allow nested functions nor dynamic scoping.
(仅提及C语言既不允许嵌套函数也不允许动态作用域。)