Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I Static and Dynamic Scoping. Consider the following program written in the C sy

ID: 3731419 • Letter: I

Question

I Static and Dynamic Scoping. Consider the following program written in the C syntax. int a, b, c, x, y, z; void print (int p) if (p-0) else if (p1) else if (p-2) printf("f: %d printf("g: %d printf ("main: %d %d %d %d %d %d %d %d %d %d ", a, %d ", a, %d %d ", b, b, a, x, x, b, z); z); y, z); y, y, x, int f(int x, int y) int a- 10 b100 c-1000; x = g(10); int y yg(x) int x; x = a+b; b -g(a) print (0); print (0) return x a-y*b+z*c; int g (int a) print (1) a = 2*a ; b = 2*b; y = 2*y; return (x t y-z) * ai int main() int c-1; a10; x = 100; y = 1000; z-f (x, y) z-g (a) print (2) return 0 1) 2) What is the output of this program if static scoping is used? What is the output of this program if dynamic scoping is used?

Explanation / Answer

Hi,

In static scoping a variable always refers to its top level environment. This is a property of the program text and unrelated to the run time call stack. whereas in dynamic scoping the compiler first searches the current block and then successively all the calling functions for the variable.

So in static scoping, we pass the values of variables at top level and below is the output:

g: 10 100 100 1000 0
g: 10 200 100 2000 0
g: 10 400 100 4000 0
f: 10 162000 100 8000 0
g: 10 162000 100 8000 0
f: 10 324000 100 16000 0
g: 10 324000 100 16000 -323580000
main: 10 648000 100 32000 -2117692592

and in dynamic scopng we pass the variable inside the functions and below is the output.

g: 10 100 100 1000 0
g: 10 200 100 2000 0
g: 10 400 100 4000 0
f: 10 162000 100 8000 0
g: 10 162000 100 8000 0
f: 10 324000 100 16000 0
g: 10 324000 100 16000 -323580000
main: 10 648000 100 32000 -2117692592

Below is the output if we do not pass values in main method for c,x, and y

g: 0 100 0 0 0
g: 0 200 0 0 0
g: 0 400 0 0 0
f: 0 0 0 0 0
g: 0 0 0 0 0
f: 0 0 0 0 0
g: 0 0 0 0 0
main: 0 0 0 0 0

Thanks.