What would the output for this be with static scoping What a

What would the output for this be with static scoping? What about with dynamic?

What would the output for this be with static scoping? What about with dynamic? # include int i; void g(); void f() {int i; i = 3; {int i; i = 2; g();} g();} void g() {i = i + 1; print f (\"g: %d\ \", i);} int main () {i = 5; g(); f(); return 0;}

Solution

a.) Static scoping means that i refers to the i declared innermost scope of declaration that has one. Since g is declared inside the global scope, the innermost i is the one in the global scope, so g will print i=6 (the global variable is changed to 5 in main and then i=i+1 changes it to 6). again when g is called in f twice it has access to the global i so it will print 7 first then 8. so output will be

g: 6

g: 7

g: 8

b.) Dynamic scoping means that i refers to the i declared in the most recent frame of the call-stack the has one. If C used dynamic scoping, g in first call would use the i from global i itself, so it will print i as 6. But in f , when first g is called most recent declred i is i=2 hence g prints i as 3 and in second call to g within f, most recent declared i is i=3 and hence it prints i as 4. so output is :

g: 6

g: 3

g: 4

What would the output for this be with static scoping? What about with dynamic? What would the output for this be with static scoping? What about with dynamic?

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site