Global variables are defined outside of a function, usually on top of
the program. The global variables will hold their value throughout the
lifetime of your program and they can be accessed inside any of the
functions defined for the program.
A global variable can be accessed by any function. That is, a global
variable is available for use throughout your entire program after its
declaration. Following is the example using global and local variables:
#include <stdio.h> /* global variable declaration */ int g; int main () { /* local variable declaration */ int a, b; /* actual initialization */ a = 10; b = 20; g = a + b; printf ("value of a = %d, b = %d and g = %d\n", a, b, g); return 0; }
A program can have same name for local and global variables but value of local variable inside a function will take preference. Following is an example:
#include <stdio.h> /* global variable declaration */ int g = 20; int main () { /* local variable declaration */ int g = 10; printf ("value of g = %d\n", g); return 0; }
When the above code is compiled and executed, it produces following result:
value of g = 10
Post a Comment