如果动态范围在 C 中是可能的,那么查找 variables和a
inside of将使用动态环境。b
c
fun2
反过来,这取决于函数的实际调用方式。由于它是从fun1
该范围的变量绑定中调用的(因此a = 2
和b = 3
)。因为fun1
已经调用 from main
,它设置了绑定c = 4
,所以输出将是2 3 4
.
另一个例子:
void fun1(void);
void fun2(void);
void fun3(void);
int a=1, b=2, c=3;
int main()
{
c=4;
fun1();
int a = 21;
fun3();
return 0;
}
void fun1()
{
int a=2, b=3;
fun2();
}
void fun2()
{
printf("%d %d %d\n", a,b,c);
}
void fun3() {
int c = 42;
fun2();
}
会打印
2 3 4
21 2 42
也许真正看到差异会对您有所帮助。Clojure 支持动态和词法作用域(这是正确的术语,顺便说一句):
(def static-scoped 21)
(def ^:dynamic dynamic-scoped 21)
(defn some-function []
(println "static = " static-scoped)
(println "dynamic = " dynamic-scoped))
(defn other-function []
(binding [dynamic-scoped 42]
(println "Established new binding in dynamic environment")
(some-function)))
;; Trying to establish a new binding for the static-scoped
;; variable won t affect the function defined
;; above.
(let [static-scoped 42]
(println "This binding won't affect the variable resolution")
(other-function))
(println "calling some-function directly")
(some-function)
(居住)
请注意,Clojure 试图尽可能地纯函数化,因此上面的代码都不是赋值(换句话说:变量的值一旦赋值就不会被修改)