What are the global variable?

What is global variable?
What is global variable?


The variables that are declared outside the main () function or may other function are called global variable or external variables. They hold their values during the entire execution of program.

The values of global variables can vet shared among different functions. If any function changes the value of a global variable, the modified value is also available to other function.

The use of global variables is not recommended, because:

They are accessible to all functions and it becomes difficult to track changes in their values.

They occupy a large amount of memory permanently during program execution and data accessing speed of program may become slow.


Scope of global variable

A global variables can be used by all functions in the programs. It has a file scope.

Lifetime of global variable

The time period for which a global variable exists in memory is called lifetime of a global variable. The lifetime of global variables in between the starting and the terminating of a program execution. The variables exist in the memory throughout the program execution.

Example
# include <stdio. h>
Int x, y, s;
Void sum (int, int);
Main(){
X=6;
Y=12;
Sum(x,y);
Pritf(“sum = “%d”, s);
}
/*definition of sum() function */
Void sum(int m, int n)
{
S=m+n;
}

In the above program, “x”, “y”, and “s” are declared as global variable. They can be  accessed in main() function as well as in “sum” function, The variables “m” and “n” are local variable of the “sum” function. The above-mentioned global variable are created when program starts excuting and destroyed from memory when program ends executing.

The “sum” function is also declared outside the main () function. It is a global function and can be used in any function of the program

What are the global variable? What are the global variable? Reviewed by JD Ahmad on June 18, 2018 Rating: 5

No comments:

Powered by Blogger.