int x; int main() { x = 14; f(); g(); } void f() { int x = 13; h(); } void g() { int x = 12; h(); } void h() { printf("%d\n",x); }
If static scoping is used, what is the result? If dynamic scoping is used, what is the result?
Now if I understand scoping right, the difference between static and dynamic scoping is that static makes variables local to a class. So the value x
would be local to void f()
, void g()
and int main ()
and dynamic would make them globally available. I'm just not sure how to apply it to this code. If static scoping was used would it only print the last value (12 from void g()
) and dynamic scoping would be using all the values of x
?
I'm a little confused on how scoping actually works. I know C
uses static scoping though.
To sum up, in static scoping the compiler first searches in the current block, then in global variables, then in successively smaller scopes. Dynamic Scoping: With dynamic scope, a global identifier refers to the identifier associated with the most recent environment and is uncommon in modern languages.
With static (lexical) scoping, the structure of the program source code determines what variables you are referring to. With dynamic scoping, the runtime state of the program stack determines what variable you are referring to.
Answer. Lexical scoping refers to when the location of a function's definition determines which variables you have access to. On the other hand, dynamic scoping uses the location of the function's invocation to determine which variables are available.
Lexical scoping (sometimes known as static scoping ) is a convention used with many programming languages that sets the scope (range of functionality) of a variable so that it may only be called (referenced) from within the block of code in which it is defined. The scope is determined when the code is compiled.
Static scoping means that x
refers to the x
declared innermost scope of declaration that has one. Since h
is declared inside the global scope, the innermost x
is the one in the global scope(it has no access to the x
s in f
and g
, since it was not declared inside them), so the program prints 14
twice.
Dynamic scoping means that x
refers to the x
declared in the most recent frame of the call-stack the has one. If C used dynamic scoping, h
would use the x
from either f
or g
- whichever one that called it - so the program would print 13
and 12
.
C/C++ doesn't use Dynamic scoping. Your programming language will use one or the other, you don't get to choose (Unless you are using Clojure! according to Idan Arye below).
Here is a great explanation/comparison with a good example: http://msujaws.wordpress.com/2011/05/03/static-vs-dynamic-scoping/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With