Redirected
7,983 views

3 Answers

Best answer
16 votes
16 votes

Note:- C uses Static Scoping(Lexical Scoping)

Scope of a variable:- The region in which a variable is accessible.

Question.->>Now if a variable is accessible then what should be its value?

This  question is answered by Scoping.

When a variable is referred  in program we should follow the following priority to associate its value:-

Scoping Static Dynamic
Priority 1 local  local
Priority 2  Ancestor  most recent active sub program

local:- If referred variable is local then in any scoping it is going to be access.

Ancestor:- In static scoping when we are not getting referred variable in local scope then search it in lower to higher ancestor block.

Most recent active sub program:-  In dynamic scoping when we are not getting referred variable in local scope then search it in the region of the function which make call to current function (keep on doing this until u get referred variable).

Conclusion:- In static scoping we can associate scope of the variable during compile time.  And in Dynamic scoping at run time.  (Thats how they got their names)

Example $\Rightarrow$

const int b = 5;

int foo() {
   int a = b + 5;
   printf("%d",a);
}

int bar() {
   int b = 2;
   return foo();
}

int main()
{
   foo(); 
   bar();
   return 0;
}

Here for static scoping $10,10$ is printed. And In dynamic scoping  $10,7$ is printed.

selected by
6 votes
6 votes

STATIC SCOPING
by default C is static scoping in this scoping firstly the value which going to be printed is looked in local scope if it is present than the values will be printed if it is not present than the values will searched in STATIA AREA(i,e int a=10,b=2) also when the program will complie the memory will be allocated to static area  and these values will remain till the program did not end .here is small example :

int a=10,b=2;
main()

{

int t=6;

printf(a,b,t);    //   here a=10 , b=2 ,t=6 will be printed becoz firstly it try to look within this red scope if it find these values  ,than                                       these value will be  printed but here it did n't find so it will print the static variables ( i,e nt a=10,b=2)

}
DYNAMIC SCOPING :

main()
{

int a=10,h=567;

d();

printf(a,h); // here a=10 ,h=567 will be printed 

}
d()

int p=90;

printf(h,p);  //            p=9 will be printed and wt for h?? h is not present in the local scope so it will look in previous local scope from                                   where this d() is being called so here h will be printed as 567.

}
now if in above dynamic program if the int p=90 is not present than it will be looked in static area in case of STATIC SCOPING but IN DYNAMIC SCOPING  it will be looked up in the previous local scope from where the function is being called..

Related questions

1 votes
1 votes
4 answers
1