Global variable

In computer programming, a global variable is a variable that is accessible in every scope. Interaction mechanisms with global variables are called global environment (see also global state) mechanisms. The global environment paradigm is contrasted with the local environment paradigm, where all variables are local with no shared memory (and therefore all interactions can be reconducted to message passing).

They are usually considered bad practice precisely because of their nonlocality: a global variable can potentially be modified from anywhere, (unless they reside in protected memory) and any part of the program may depend on it. A global variable therefore has an unlimited potential for creating mutual dependencies, and adding mutual dependencies increases complexity. See Action at a distance. However, in a few cases, global variables can be suitable for use. For example, they can be used to avoid having to pass frequently-used variables continuously throughout several functions.

Global variables are used extensively to pass information between sections of code that don't share a caller/callee relation like concurrent threads and signal handlers. Languages where each file defines an implicit namespace eliminate most of the problems seen with languages with a global namespace though some problems may persist without proper encapsulation. Without proper locking (such as with a mutex), code using global variables will not be thread-safe except for read only values in protected memory.

An example of a global variable in C++:
#include

using namespace std;

int global = 3; // This is the global variable.

void ChangeGlobal(){ global = 5; // Reference to global variable in a function.}

int main(){ cout << global << endl; // Reference to global variable in another function. ChangeGlobal(); cout << global << endl; return 0;}As the variable is a global one, there is no need to pass it as a parameter to use it in a function besides main. The global variable belongs to every function in the program.

The output will be: 3 5

The use of global variables makes software harder to read and understand. Since any code anywhere in the program can change the value of the variable at any time, understanding the use of the variable may entail understanding a large portion of the program. They make separating code into reusable libraries more difficult because many systems (such as DLLs) don't directly support viewing global variables in other modules. They can lead to problems of naming because a global variable makes a name dangerous to use for any other local or object scope variable. A local variable of the same name can shield the global variable from access, again leading to harder to understand code. The setting of a global variable can create side effects that are hard to understand and predict. The use of globals make it more difficult to isolate units of code for purposes of unit testing, thus they can directly contribute to lowering the quality of the code.

If a variable in a function is not defined, then it is automatically considered as a global variable. The current value of this variable is used in the function. Functions can be invoked with less input or output parameters.

Some languages, like Java, don't have global variables. In Java, all variables that are not local variables are fields of a class. Hence all variables are in the scope of either a class or a method. In Java, static fields (aka class variables) exist independently of any instances of the class and one copy is shared among all instances; hence static fields are used for many of the same purposes as global variables in other languages because of their similar "sharing" behavior.

See also

*Variables
**Static variable
**External variable
*Singleton pattern

References

*William Wulf and Mary Shaw, “Global Variable Considered Harmful”, ACM SIGPLAN Notices, volume 8, issue 2, 1973 February, pp. 28-34.


Wikimedia Foundation. 2010.

Look at other dictionaries:

  • global variable — noun (computing) A variable which applies for the whole of a program, including any subroutine • • • Main Entry: ↑globe …   Useful english dictionary

  • global variable — UK US noun [C] IT ► a symbol used in a computer program that can represent any data …   Financial and business terms

  • global variable — globalusis kintamasis statusas T sritis informatika apibrėžtis Kintamasis, kurio vardas aprašytas programos pagrindinėje dalyje ir galiojantis visoje programoje, išskyrus tuos programos blokus, kuriuose toks pat vardas aprašytas iš naujo. Per… …   Enciklopedinis kompiuterijos žodynas

  • Global — is a synonym of worldwide and means of, or relating to, or involving the entire world, in the general sense or as the planet Earth. [ [http://dictionary.oed.com/cgi/entry/50095613?single=1 query type=word queryword=Global first=1 max to show=10… …   Wikipedia

  • global — glob al adj. 1. involving the entire earth; not limited or provincial in scope; as, global war; global monetary policy. Syn: planetary, worldwide. [WordNet 1.5] 2. shaped like a globe; spherical. Syn: ball shaped, globose, globular, orbicular,… …   The Collaborative International Dictionary of English

  • Variable global — Una variable global es, en informática, una variable accesible en todos los ámbitos de un programa informático. Los mecanismos de interacción con variables globales se denominan mecanismos de entorno global. El concepto de entorno global… …   Wikipedia Español

  • Variable — A variable (pronEng|ˈvɛərɪəbl) is an attribute of a physical or an abstract system which may change its value while it is under observation. Examples include the height of a child, the temperature across a state, or the input to a function. This… …   Wikipedia

  • Global.asax — is an optional file used to declare and handle application and session level events and objects. Global.asax is the ASP.NET extension of the ASP Global.asa file. The Global.asax file resides in the IIS virtual root of an ASP.NET application. At… …   Wikipedia

  • Global.asax — es un archivo opcional usado en las aplicación web de ASP.NET para declarar y manejar eventos y objetos a nivel de aplicación y de sesión. Global.asax es la extensión de archivo Global.asa utilizado en ASP. El archivo Global.asax reside en el… …   Wikipedia Español

  • Global warming controversy — refers to a variety of disputes, significantly more pronounced in the popular media than in the scientific literature,[1][2] regarding the nature, causes, and consequences of global warming. The disputed issues involve the causes of increased… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”