*** Welcome to piglix ***

Global variables


In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state. In compiled languages, global variables are generally static variables, whose extent (lifetime) is the entire runtime of the program, though in interpreted languages (including command-line interpreters), global variables are generally dynamically allocated when declared, since they are not known ahead of time.

In some languages, all variables are global, or global by default, while in most modern languages variables have limited scope, generally lexical scope, though global variables are often available by declaring a variable at the top level of the program. In other languages, however, global variables do not exist; these are generally modular programming languages that enforce a module structure, or class-based object-oriented programming languages that enforce a class structure.

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 non-locality: a global variable can potentially be modified from anywhere (unless they reside in protected memory or are otherwise rendered read-only), 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. Global variables also make it difficult to integrate modules because software written by others may use the same global names unless names are reserved by agreement, or by naming convention. 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. In practice, large programs may well require a large number of global variables because there are so many parameters that are shared between different functions, and care must be taken to make sure different functions share the global data without mishap.


...
Wikipedia

...