Thursday, January 5, 2012

Local And Global Variables


Local And Global Variables
The variables in general may be classified as local or global variables.
 (a) Local variables  Identifiers declared as label, const, type, variables and functions in a block are said to a particular block are said to belong to a particular block or function and these identifiers are known as the local parameters or variables. Local variables are defined inside a function block or a compound statement.
   For example,
        void funct (int i, int j)
      {
           int k,m; / / local variables





                       / / body of the function
       }
  The integer variables k and m are defined within a function block of the funct (). All the variables to be used within a function block must be either defined at the beginning of the block itself or before using in a statement. Local variables are referred only the particular part of a block or a function. Same variable name may be given to different parts of a block or a function. Some variable will be treated as a different entity.
   For example,
          functionl (float a, float b)
        {
               float x,y; / / local variable
               x = 10.101;
               y = 20.20;



                / / body of the function 1
        }
        function2 (int i, int j)
        }
              float x,y; / / local to the function 2
              x = 1.111;
              y = 2.2222;


                              
              / / body of the function 2
        }
(b)  Global variables  Global variables are variables defined outside the main function block. These variables are referred by the same data type and by the same name through out the program and in the calling portion of a program and in the function block. Whenever some of the variables are treated as constants in both the main and the function block, it is advisable to use global variables.
    For example,
          int x,y = 4; / / global declaration
        void main (void)
        {
               void functionl ( );
               x = 10;


               
               functionl ( );
        }
        functionl ( );
        {
               int sum;
               sum = x+y;


                  
        }

PROGRAM
A program to find the  sum of the given two numbers using the global variable declaration.
    / / global variables declaration
   #includ <iostream.h>
   int x;
   int y = 5;
   void main (void);
      {
          x = 10;
          void sum (void);
          sum ( );
      }
void sum (void)
{
   int sum;
   sum = x+y;
   cout << “ x = “ << x << endl ;
   cout << “ y = “ << y << endl ;
   cout << “ sum = “ << sum << endl ;
}
Output of the above program
   x = 10
   y = 5
  sum = 15

1 comment: