Explain External Variable with program and Example, Difference between local and global variable

 Explain External Variable with program and Example, Difference between local and global variable

Global Variable

Variables that are both alive and active throughout the entire program are known as external variables.
They are also known as global variables.
Unlike local variables, global variables can be accessed by any function in the program.
External variables are declared outside a function.


       int number;
       float length =7.5;
      void main( )
     {
        …………..
       …………..
     }
     function1( )
    {
       …………..
       …………….
    }
    function2( )
   {
     ……………
      ……………
  }
In case a local variable and a global variable have the same name, the local variable will have precedence over the global one in the function where it is declared.
int count;
  void  main( )
  {
    count=10;
    ………..
    ………….
  }
  function()
  {
    int count=0;
    count=count+1;
    ……………
  }
Once a variable has been declared as global, any function can use it and change its value.
Then subsequent functions can reference only that new value.
One another aspect of a global variable is that it is available only from the point of declaration to the end of the program.
For example :
 void main( )
  {
     y=5;
     ………
     ………..
  }
  int y;
 func1( )
  {
   y=y+1;
  }

void main( )
{
   extern int y;
  …………..
  ……………
}
func1( )
{
  extern int y;
………………
}
int y;
Although the variable y has been defined after both the functions, the external declaration of y inside the functions informs the compiler that y is an integer type defined somewhere else in  the program.
The extern declaration does not allocate storage space for variables.
In case of array the definition should include their size as well.

Labels: