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.