What is Local Variable and Scope in C Programming?



What is Local Variable ?

  1. Local Variable is Variable having Local Scope.
  2. Local Variable is accessible only from function or block in which it is declared .
  3. 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 :

  1. 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
  2. Similarly Variables declared inside inner block are visible or meaningful only inside Inner block.
  3. 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 :

[box]Inner Block can access variables declared inside Outer Block[/box]
[box]Outer block can’t access variables declared inside Inner Block[/box]