Home      Discussion      Topics      Dictionary      Almanac
Signup       Login
Global variable

Global variable

Overview
In computer programming
Computer programming
Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language. The code may be a modification of an existing source or something completely new...

, a global variable is a variable that is accessible in every scope
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them -- or semantics...

. 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
Shared memory
In computing, shared memory is memory that may be simultaneously accessed by multiple programs with an intent to provide communication among them or avoid redundant copies. Depending on context, programs may run on a single processor or on multiple separate processors...

 (and therefore all interactions can be reconducted to message passing
Message passing
Message passing in computer science, is a form of communication used in parallel computing, object-oriented programming, and interprocess communication.- Overview :...

).

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.
Discussion
Ask a question about 'Global variable'
Start a new discussion about 'Global variable'
Answer questions from other users
Full Discussion Forum
 
Encyclopedia
In computer programming
Computer programming
Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language. The code may be a modification of an existing source or something completely new...

, a global variable is a variable that is accessible in every scope
Scope (programming)
In computer programming, scope is an enclosing context where values and expressions are associated. Various programming languages have various types of scopes. The type of scope determines what kind of entities it can contain and how it affects them -- or semantics...

. 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
Shared memory
In computing, shared memory is memory that may be simultaneously accessed by multiple programs with an intent to provide communication among them or avoid redundant copies. Depending on context, programs may run on a single processor or on multiple separate processors...

 (and therefore all interactions can be reconducted to message passing
Message passing
Message passing in computer science, is a form of communication used in parallel computing, object-oriented programming, and interprocess communication.- Overview :...

).

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.

The use of global variables is particularly bad for functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...

 languages (such as Scheme). It violates referential transparency and makes it very difficult to analyze code.

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
Namespace
In general, a namespace is an abstract container providing context for the items it holds and allowing disambiguation of homonym items having the same name ....

 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
Thread-safe
Thread safety is a computer programming concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads....

 except for read only values in protected memory.

An example of a global variable in C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features...

:
  1. include


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

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

int main
{
std::cout << global << '\n'; // Reference to global variable in another function.
ChangeGlobal;
std::cout << global << '\n';
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 DLL
DLL
DLL is an abbreviation which can commonly mean:* Data link layer, a layer in the OSI network architecture model* Delay-locked loop, a device to reduce clock skew in digital circuits* Doubly-linked list, a data structure in computer programming...

s) 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
    Variable (programming)
    In computer programming, a variable is a facility for storing data. The current value of the variable is the data actually stored in the variable. Depending on the programming language in question, the data stored in the variable can be intentionally altered during the program run. This is why it...

    • Static variable
      Static variable
      In computer programming, a static variable is a variable that has been allocated statically — whose lifetime extends across the entire run of the program...

    • External variable
      External variable
      In the C programming language, an external variable is a variable defined outside any function block. On the other hand, a local variable is a variable defined inside a function block.- Definition, declaration and the extern keyword :...

  • Singleton pattern
    Singleton pattern
    In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system...

  • Local variable
    Local variable
    In computer science, a local variable is a variable that is given local scope. Such a variable is accessible only from the function or block in which it is declared. Local variables are contrasted with global variables....