static scoping and dynamic scoping

本文探讨了静态作用域(也称词法作用域)与动态作用域的区别。静态作用域中变量绑定与其声明位置相关,而动态作用域则依赖于运行时调用堆栈。通过示例代码展示了不同作用域下变量解析的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Static Scoping:

With static scope, a variable always refers to its top-level environment. This is a property
of the program text and unrelated to the runtime call stack. Because matching a variable 
to its binding only requires analysis of the program text, this type of scoping is sometimes 
also called lexical scoping. Static scope is standard in modern functional languages such as 
ML because it allows the programmer to reason as if variable bindings are carried out by
substitution.


Static scoping also makes it much easier to make modular code and reason about it, since 
its binding structure can be understood in isolation. In contrast, dynamic scope forces the 
programmer to anticipate all possible dynamic contexts in which the module's code may
be invoked.


In other words, a language uses static scope or lexical scope if it is possible to determine 
the scope of a declaration by looking only at the program. Otherwise, the language uses
dynamic scope


Dynamic Scoping:

With dynamic scope, each identifier has a global stack of bindings. Introducing a local
variable with name x pushes a binding onto the global x stack (which may have been 
empty), which is popped off when the control flow leaves the scope. Evaluating x in any 
context always yields the top binding. In other words, a global identifier refers to the 
identifier associated with the most recent environment. Note that this cannot be done at 
compile time because the binding stack only exists at runtime
, which is why this type of
scoping is called dynamic scoping.


Static Scope:

$x = 100;


sub foo()
{
my $x = 10;
goo();
print "the first x is: $x\n";
}


sub goo()
{
my $x = 20;
hoo();
}


sub hoo()
{
my $x = 30;
print "the second x is: $x\n";
}


foo();
print "the third one is: $x\n";

输出结果:

the second x is: 30

the first x is:10

the third one is: 100



$x = 100;


sub foo()
{
my $x = 10;
goo();
print "the first x is: $x\n";
}


sub goo()
{
$x = 20;
hoo();
}


sub hoo()
{
$x = 30;
print "the second x is: $x\n";
}


foo();
print "the third one is: $x\n";


输出结果:

the second x is: 30

the first x is:10

the third one is: 30




Dynamic Scope:

$x = 100;


sub foo()
{
local $x = 10;
goo();
print "the first x is: $x\n";
}


sub goo()
{
$x = 20;
hoo();
}


sub hoo()
{
$x = 30;
print "the second x is: $x\n";
}


foo();
print "the third one is: $x\n";

输出结果:

the second x is: 30

the first x is:30

the third one is: 100



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值