Programming Techniques:Global Variables
From GPWiki
[edit] Global VariablesA 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:
#include <iostream> int iVar = 1; // creates a global variable useable anywhere in the program int main() { std::cout << "iVar is: " << iVar << std::endl; } [edit] AlternativesSeveral uses of global variables are unnecessary -- they can be turned into non-global variables. [edit] Local VariablesIn 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; } [edit] The Singleton PatternA 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. [edit] Passing by ParameterWhen 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. [edit] See Also |


