Functions : Scope of a variable - Global Variable

Scope of a variable continued

Global Variables  are variables declared outside all the function. It is accessible in all function including main and other user defined function. Global variables are created when the main program execution begins and removed from after completing the execution of a main program hence its value persists until the main program execution completes.

Example : 

# include < stdio.h >
int g=10;

Test ( )
{
g = g + 10;
}
Sample ( )
{
g = g * 10;
}
main ( )
{
printf ( " \n Global variable g = %d ", g);

Test ( );
printf ( " \n Global variable g = %d ", g);

Sample ( );
printf ( " \n Global variable g = %d ", g);



In the beginning of above program a variable g is declared with value 10. When the main() program execution starts g value is printed i.e. 10. Then Test() is called. In the function definition of Test() observe g is not declared once again. It is using global variable g. Value 10 is added to global variable g. In main() value of g is printed i.e. 20. Then Sample() is called from main(). In function definition value 10 is multiplied with current value of g i.e. 20. Then in main() value of g is printed i.e. 200. We see that global variable g is being accessed in all function without re-declaring it. Its value is preserved until the main() execution completes.
                                                                                     continued...

Comments