Programming Techniques:Global Variables

From GPWiki
Jump to: navigation, search

Global Variables

A Global Variable is a container that is accessible from anywhere throughout the scope of a program, usually kept alive until the program ends. Typically implimented in small programs to allow a single variable to spans multiple functions, as opposed to having separate Local Variables copies of it. Global Variables can be problematic, affecting:

  • Intended Value - Multiple functions that modify the value of the global variable, whether directly or via a reference, such as a pointer (also known as aliasing), become dependent that the modification is desired to the functions accessing the value after that, meaning the changes may be unintended.
  • Readability - A global variable's declaration may be far-removed from the location that it is accessed from, and the code that is dependent on it, making it difficult to follow. Also a global variable's name may be generic and resemble similarly named local variables.
#include <iostream>
 
int iVar = 1;     // creates a global variable useable anywhere in the program
 
int main()
{
   std::cout << "iVar is: " << iVar << std::endl;
}

Alternatives

Several uses of global variables are unnecessary -- they can be turned into non-global variables.

Local Variables

In a case where a Global Variable is being used in a single scope and could exist only in that scope. There is no need for the variable to be global, you can use Local Variables instead, that is, variables that exist only within the functions they're created in.

#include <iostream>
 
int main()
{
   int iVar = 1;     // creates a local variable useable anywhere in the main() function
   std::cout << "iVar is: " << iVar << std::endl;
}

The Singleton Pattern

A common misconception is that using the Singleton for a global variable makes it less global. This is not the case; however, it does solve the problem of controlling the lifetime of the global variable. Using a Singleton, the code that creates and initializes the variable does not need to know about the code that uses it, and the code that uses it does not need worry about the lifetime of the variable. This removes a critical (yet indirect) interdependency between two otherwise unrelated blocks of code.

Passing by Parameter

When calling a function, the value of a variable or a reference to a variable can be passed as a parameter. This eliminates the need for the variable to be accessed directly, and removes a dependency.

See Also

http://en.wikipedia.org/wiki/Global_variable