-2

我的老师提供了以下伪代码,并说使用静态范围的输出是1 2 3,但使用动态范围的输出是2 3 4

挑战在于静态作用域我们使用a=1, b=2, c=3 不注意main or no,使用a=1, b=2, c=4?仅在静态范围内,不包括 C 规则。

void fun1(void);
void fun2(void);

int a=1, b=2, c=3;

int main() {
    c=4;
    fun1();
    return 0;
}

void fun1() {
    int a=2, b=3;
    fun2();
}

void fun2(){
    printf("%d%d%d", a,b,c);
}
4

1 回答 1

0

如果动态范围在 C 中是可能的,那么查找 variables和ainside of将使用动态环境。bcfun2

反过来,这取决于函数的实际调用方式。由于它是从fun1该范围的变量绑定中调用的(因此a = 2b = 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 试图尽可能地纯函数化,因此上面的代码都不是赋值(换句话说:变量的值一旦赋值就不会被修改)

于 2016-02-11T23:35:29.733 回答