Global Variables:
The variables that are declared outside the main function or any other function are called global variables or external variables. These variables can he accessed in any function at any time during execution of the program. The global variables are used when variables are to he accessed by more than one function in a program. The global variables arc not normally used in program because:
- Since they are accessible to all functions, it is difficult to track changes in their values.
- They occupy a large amount of memory permanently during program execution and the data accessing speed of program becomes slow.
Life-Time of Global Variables:
The global variables exist in the memory throughout the program execution. They are created into the memory when the program execution starts. They are destroyed only when the program ends. Therefore, the lifetime of the global variables is between the starting and the termination of the program. A program example is given that uses global as well as local variables.
Program:
# include <iostream.h>
int a, b, s;
main ( )
void sum (int, int);
a = 10;
b = 100;
sum(a, b);
cout << “sum= ” << s
cout << “ok”;
}
void sum (int x , int y)
{
s = x + y;
}
In the above program, a, b and s variables are declared as global variables and are outside the main function. These can he accessed in the function sum (as defined above) as well as in the main function. The variables x and y are local variables of function “sum”.
comment closed