in Programming in C
583 views
1 vote
1 vote
what will be the output of the code please elaborate the scopes ?

#include<stdio.h>
int a=10,b=20;
C(){  a=23;
      printf("%d %d\n",a,b);
      D();
      a=6,b=7;
   }
D(){  b=44;
     E();
     printf("%d %d\n",a,b);

   }
E(){
     printf("%d %d\n",a,b);
      a=1,b=2;
    }
int main()
{
    int a=5,b=6;
    C();
    a=2,b=3;
    E();
    printf("%d %d\n",a,b);
    
    return 0;
}
in Programming in C
583 views

11 Comments

23 20

23 44

1 2

6 7

2 3
0
0
how??

 u r telling in Static scoping ,right?
0
0
In dynamic scoping

23,20

10,20

10,44

10, 20

2,3

because code  evaluate code top-down
1
1
i got the answer running this code i need an explanation how you got 7 in fourth line

Or can you suggest any source to clear static and dynamic scoping .
0
0

@hitendra: Bro, let me explain you how global a & b values changing:

a = 10 , b = 20

after line C() of main

a = 23 , b = 20 (1st line of output)

Now C() calling D(), which caused b to be changed. So

a = 23 , b = 44 (2nd line of output)

Now D() calling E() which prints 2nd line of output,and then changing value of a & b

a = 1, b = 2 (3rd line of output)

Now Backtracking starts , so D() prints current global value which is above

Then C() comes into picture after D() is over, which changes global value again,

a = 6, b = 7 

Now , main() comes into picture which has local a (we represent it as aL) and(we represent it as bL), so

aL = 2 , bL = 3 (It is different from global a & b)

Again we are calling E(), which prints current global value and also changing values too.

a = 6, b = 7 (4th line of output) and changes values also, so

a = 1 , b = 2

and we are back to main() , so printing local values as main() referred its local ONLY,so

a = 2 , b= 3 (5th line of output) which is nothing but aL = 2 , bL = 3.

Hence final output is 

23 20

23 44

1 2

6 7

2 3

0
0

srestha explains the execution sequence for dynamic scoping??

 
 
0
0

@Abbas

Is your answer in relevance to dynamic scoping?

0
0

but how can the first line be 23,20 it would rather be 23, 6 because as per kiran sir's lecture in dynamic scoping if you dont get a variable while executing a block the back track the sequence of execution  untill you find the value so that value of b would 6 instead of 20

0
0
in dynamic scoping the output will be

23,6

23,44

1,2

2,3

1,2
2
2

hitendra singh your output using dynamic scope is correct 

0
0

Please log in or register to answer this question.