1,973 views
1 votes
1 votes
#include<stdio.h>

int x=10;

int main()
{
    static int x=10;
    x+=f1()+f2()+f3()+f1();
    printf("%d",x);
    return 0;
}

int f1(){static int x=25;x++;return x;}
int f2(){int x=50;x++;return x;}
int f3(){x*=10;return x;}

What is the output of the above code, if dynamic scoping is used.

2 Answers

2 votes
2 votes

  

    x = x + f1() + f2() + f3() + f1();
    x = 10 + 26 + 51 + 100 + 27
    x = 214
/* x is static local variable of main function and its value is 10.
f1() also access its local static variable value that is 25 after increment 26.
f2() access its local variable value that is 50 after increment 51.
f3() access global variable value that is 10 because C uses static scoping. And In dynamic scoping, f3() will access local static variable of main function
f1() access its local static variable which is available throughout the program */
1 votes
1 votes

Expression is x+=f1()+f2()+f3()+f1();

if we expand this expression it look like below 

x=x+ f1()+f2()+f3()+f1();  here the tricky part actually, x=x+ (some value)

static int x =10 

x = x + f1() +f2() + f3() + f1()

f1() -->26 

x = x + 26 +f2() + f3() + f1()

f2() -->51

x = x + 26 + 51 + f3() + f1()

f3() -->100 // makes global "x =100" (imp point to note) , not static value inside the main method

x = x + 26 +51 + 100 + f1()

f1() -->27

x = x + 26 + 51 + 100 + 27

Now it's time to choose the x value in main method (variable scope) , it will consider the static  variable inside the main method 

so it's value is still 10 (x=10)

x = 10+ 26 +51 + 100 + 27 = 214

Answer must be 214.

if still not able understand the flow , just delete the static declaration inside the main method and execute the program , you will see the difference and what's scope of static variable inside the main method.

Related questions

3 votes
3 votes
2 answers
1
set2018 asked Oct 10, 2017
446 views
int i=10;main(){int i =5,k,i=6;printf("enter value");scanf("%d",&k);if(k>0){fun1();}else{fun2();}}void fun1();{printf("%d",i);}void fun2();{int i=5;printf("%d",i);fun1();...
3 votes
3 votes
1 answer
3
dragonball asked Jan 14, 2018
880 views
How to solve any dynamic scoping question . Plz describe in detail.