Concept of Progamming Languages 10th Edition (Robert W. Sebesta) International E
ID: 3661668 • Letter: C
Question
Concept of Progamming Languages 10th Edition (Robert W. Sebesta) International Edition
CH5 => 6PS (Problem Set)
6. Consider the following JavaScript skeletal program:
//The main program
function sub1(){
var x;
function sub2(){
...
}
}
function sub3(){
....
}
Assume that the execution of this program is in the following unit order:
main calls sub1
sub1 calls sub2
sub2 calls sub3
Question:
a. assuming static scoping, in the following, which declaration of x is the correct one for reference to x?
i. sub1
ii. sub2
iii. sub3
b. Repeat part a, but assume dynamic scoping.
Explanation / Answer
Static Scoping – Variables can be bound at compile time without regards to calling code.
Dynamic Scoping – Variable binding (context) can only be determined at the moment code is executed.
C, C++, C#, and JavaScript all use static scoping, whereas Perl and Logo allow dynamic scoping though their local keyword.
Examples:
Static Scoping
const int b=5;
int foo()
{ int a=b+5;
return a;}
int bar() {
int b=2;
return foo(); }
int main() {
foo(); //returns 10
bar(); //returns 10
return 0;
}
Dynamic Scoping
const int b=5;
int foo()
{ int a=b+5;
return a;}
int bar() {
int b=2;
return foo(); }
int main() {
foo(); //returns 10
bar(); //returns 7
return 0;
}
Now Consider the following JavaScript skeletal program:
//The main program
function sub1(){
var x;
function sub2(){
...
}
}
function sub3(){
....
}
In case of static scoping---
Here in case of function sub1 and sub2, the concept of nested scope will be applied i.e. the direct scope of x in function sub1 but it is also accessible in the nested scope function sub2, so for function sub1 and sub2 , the declaration of x in function sub1 is correct
but in case of function sub3 , the variable x would not be accessible , so for function sub3 the declaration of x in function sub1 is incorrect , it should be in main function
i.e. sub1: sub1
sub2: sub1
sub3: main
In case of dynamic scoping---
As for function sub1 and function sub2 , the concept of nested scope is applicable, so the result also remains the same i.e. for function sub1 and sub2 , the declaration of x in function sub1 is correct.
but for function sub3 in case of dynamic scoping, the correct declaration of x should be in function sub1 because here we are calling function sub3 from function sub2 , so function sub3 would inherit scope from function sub2 and function sub2 inheriting scope (nested scope) from function sub1 so ultimately function sub3 inheriting scope from function sub1
i.e. sub1: sub1.
sub2: sub1
sub3: sub1
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.