What is Local Variable and Scope in C Programming?
What is Local Variable ?
- Local Variable is Variable having Local Scope.
- Local Variable is accessible only from function or block in which it is declared .
- Local variable is given Higher Priority than the Global Variable.
Above Fig. Tells us that - Above Program has 2 blocks i.e Inner Block and Outer Block
Facts about Local Variable :
- Variables declared inside outer block are visible or meaningful only inside outer block.
- Example : var1 is Local to Outer Block.
- var1 cannot be accessed from its outer block.
- var1 cannot be accessed from Other Function or other block
- var1 can be accessed from inner block
- Similarly Variables declared inside inner block are visible or meaningful only inside Inner block.
- Variables declared inside inner block are not accessed by outer block . i.e
#include<stdio.h> void main() { int var1=10; { int var2 = 20; printf("%d %d",var1,var2); // Legal : var1 can be accessed } printf("%d %d",var1,var2); // Error : var2 is not declared }
Short Summary :
Inner Block can access variables declared inside Outer Block
Outer block can’t access variables declared inside Inner Block