Tuesday, September 21, 2010

Global Variables

Unlike local variables, global variables are known throughout the program and may be
used by any piece of code. Also, they will hold their value throughout the program's
execution. You create global variables by declaring them outside of any function. Any
expression may access them, regardless of what block of code that expression is in.
In the following program, the variable count has been declared outside of all
functions. Although its declaration occurs before the main() function, you could have
placed it anywhere before its first use as long as it was not in a function. However, it is
usually best to declare global variables at the top of the program.
#include <stdio.h>
int count; /* count is global */
void func1(void);
void func2(void);
int main(void)
{
count = 100;
func1();
return 0;
}
void func1(void)
{
int temp;
temp = count;
func2();
printf("count is %d", count); /* will print 100 */
}
void func2(void)
{
int count;
for(count=1; count<10; count++)
putchar('.');
}
Look closely at this program. Notice that although neither main() nor func1() has
declared the variable count, both may use it. func2() , however, has declared a local
variable called count. When func2() refers to count, it refers to only its local variable,
not the global one. If a global variable and a local variable have the same name, all
references to that variable name inside the code block in which the local variable is
declared will refer to that local variable and have no effect on the global variable.
This can be convenient, but forgetting it can cause your program to act strangely,
even though it looks correct.
Storage for global variables is in a fixed region of memory set aside for this purpose
by the compiler. Global variables are helpful when many functions in your program
use the same data. You should avoid using unnecessary global variables, however.
They take up memory the entire time your program is executing, not just when they are
needed. In addition, using a global where a local variable would do makes a function
less general because it relies on something that must be defined outside itself. Finally,
using a large number of global variables can lead to program errors because of unknown and unwanted side effects. Amajor problem in developing large programs is the
accidental changing of a variable's value because it was used elsewhere in the program.
This can happen in C/C++ if you use too many global variables in your programs.

No comments:

Post a Comment