My teacher has provided the following pseudo-code, and says that the output using static scope is 1 2 3
, but the output using dynamic scope is 2 3 4
.
The Challenge is in Static Scope we use a=1, b=2, c=3 without attention to main or no, use a=1, b=2, c=4? Just in Static Scope without including C Rules.
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);
}
If dynamic scope were possible in C, then lookup of the variables a
, b
and c
inside of fun2
would use the dynamic environment.
This, in turn, depends on how the function got actually called. Since it's called from fun1
the variable bindings of that scope will be used (thus a = 2
and b = 3
). Because fun1
had been called from main
, which set up the binding c = 4
, the output would be 2 3 4
.
Another example:
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();
}
Would print
2 3 4
21 2 42
Perhaps actually seeing the difference helps you. Clojure supports both dynamic and lexical scoping (this is the correct terminology, btw):
(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)
Note that Clojure tries to be as purely functional as possible, thus none of the code above is a assignment (in other words: the values of the variables aren't modified once assigned)