Global variable
Encyclopedia
In computer programming
Computer programming
Computer programming is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs. This source code is written in one or more programming languages. The purpose of programming is to create a program that performs specific operations or exhibits a...

, 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...

 (unless shadowed
Variable shadowing
In computer programming, variable shadowing occurs when a variable declared within a certain scope has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed...

). 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. In this model, processes or objects can send and receive messages to other processes...

).

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
Read-only
In computing, read-only can mean:* Read-only memory , a type of storage media* Read-only access to files or directories in file system permissions...

), 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
Action at a distance (computer science)
Action at a distance is an anti-pattern in which behavior in one part of a program varies wildly based on difficult or impossible to identify operations in another part of the program....

. 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 do not share a caller/callee relation like concurrent threads and signal handlers. Languages (including C) 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 a container that provides context for the identifiers it holds, and allows the disambiguation of homonym identifiers residing in different namespaces....

 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 only manipulates shared data structures in a thread-safe manner, which enables safe execution by multiple threads at the same time...

 except for read only values in protected memory.

C and C++

The C language does not have a global keyword
Keyword (computer programming)
In computer programming, a keyword is a word or identifier that has a particular meaning to the programming language. The meaning of keywords — and, indeed, the meaning of the notion of keyword — differs widely from language to language....

. However, variables declared outside a function implicitly have a scope covering everything in the .c file or compilation unit containing its declaration. In a small program contained in a single file, such variables effectively have global scope. On the other hand, a variable that is required to have global-scope in a multi-file project needs to imported individually into each file using the extern keyword. Such global access can be made implicit by placing the extern declaration in a shared header file, since it is common practice for all .c files in a project to include at least one .h file: the standard header file errno.h is an example, making the errno variable accessible to all modules in a project. Where this global access mechanism is judged problematic, it can be disabled using the static keyword which restricts a variable to file scope, and will cause attempts to import it with extern to raise a compilation error.

An example of a "global" variable in C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

:

/* Note that this example is correct.
global does not qualify as a global variable as it is not "in scope everywhere".
*/
  1. include


int myGlobal = 3; /* This is the external variable. */

static void ChangeMyGlobal(void)
{
myGlobal = 5; /* Reference to external variable in a function. */
}

int main(void)
{
printf("%d\n", myGlobal); /* Reference to external variable in another function. */
ChangeMyGlobal;
printf("%d\n", myGlobal);
return 0;
}

As the variable is an external one, there is no need to pass it as a parameter to use it in a function besides main. It belongs to every function in the module.

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
Dynamic-link library
Dynamic-link library , or DLL, is Microsoft's implementation of the shared library concept in the Microsoft Windows and OS/2 operating systems...

) 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.

Environment variables

Environment variables are a facility provided by some operating systems. Within the OS's shell
Shell (computing)
A shell is a piece of software that provides an interface for users of an operating system which provides access to the services of a kernel. However, the term is also applied very loosely to applications and may include any software that is "built around" a particular component, such as web...

 (ksh
Korn shell
The Korn shell is a Unix shell which was developed by David Korn in the early 1980s and announced at USENIX on July 14, 1983. Other early contributors were AT&T Bell Labs developers Mike Veach, who wrote the emacs code, and Pat Sullivan, who wrote the vi code...

 in Unix
Unix
Unix is a multitasking, multi-user computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna...

, bash in Linux
Linux
Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of any Linux system is the Linux kernel, an operating system kernel first released October 5, 1991 by Linus Torvalds...

, command.exe in DOS
DOS
DOS, short for "Disk Operating System", is an acronym for several closely related operating systems that dominated the IBM PC compatible market between 1981 and 1995, or until about 2000 if one includes the partially DOS-based Microsoft Windows versions 95, 98, and Millennium Edition.Related...

 and cmd.exe
Cmd.exe
Command Prompt is the Microsoft-supplied command-line interpreter on OS/2, Windows CE and on Windows NT-based operating systems...

 in Windows) they are a kind of variable: for instance, in unix and related systems and ordinary variable becomes an environment variable when the export keyword is used. Program code other than shells has to access them by API calls, such as
getenv and setenv.

They are local to the process in which they were set. That means if we open two terminal windows (Two different processes running shell) and change value of environment variable in one window, that change will not be seen by other window.

When a child process is created, it inherits all the environment variables and their values from the parent process. Usually, when a program calls another program, it first creates a child process by forking, then the child adjusts the environment as needed and lastly the child replaces itself with the program to be called. Child processes therefore cannot use environment variables to communicate with their peers, avoiding the action at a distance problem.

Java: no explicit globals

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.

PHP: globals and superglobals

PHP
PHP
PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...

 has a global keyword and a number of unusual ways of using global variables.
Variables declared outside functions have file scope (which is for most purposes the widest scope). However, they are not accessible inside functions unless imported with the global keyword (i.e., the keyword accesses global variables, it does not declare) them. However, some predefined variables, known as superglobals are always accessible.
They are all arrays. A general purpose one is the $GLOBALS superglobal, which contains all the variables
defined out of function scope. Changes to its elements change the original variables, and additions create new variables.
The superglobals $_POST and $_GET are widely used in web programming.

Global-only and global-by-default

A number of non-structured
Structured programming
Structured programming is a programming paradigm aimed on improving the clarity, quality, and development time of a computer program by making extensive use of subroutines, block structures and for and while loops - in contrast to using simple tests and jumps such as the goto statement which could...

 languages, such as (early versions of) BASIC
BASIC
BASIC is a family of general-purpose, high-level programming languages whose design philosophy emphasizes ease of use - the name is an acronym from Beginner's All-purpose Symbolic Instruction Code....

, COBOL
COBOL
COBOL is one of the oldest programming languages. Its name is an acronym for COmmon Business-Oriented Language, defining its primary domain in business, finance, and administrative systems for companies and governments....

 and Fortran
Fortran
Fortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...

 only provide global variables. Variables are global by default in FORTH
Forth
Forth is a structured, imperative, reflective, concatenative, extensible, stack-based computer programming language and programming environment...

, lua and most command shells.

Other languages

  • In Python
    Python (programming language)
    Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

     a global variable can be declared anywhere with the global keyword.
  • Ruby
    Ruby (programming language)
    Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...

    's global variables are distinguished by a '$' sigil
    Sigil (computer programming)
    In computer programming, a sigil is a symbol attached to a variable name, showing the variable's datatype or scope. In 1999 Philip Gwyn adopted the term "to mean the funny character at the front of a Perl variable".- Historical context:...

    . A number of predefined globals exist, for instance $$ is the current process ID.

See also

  • Variables
    Variable (programming)
    In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...

    • 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 used to implement the mathematical concept of a singleton, by restricting the 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. In programming languages with only two levels of visibility, local variables are contrasted with global variables...

  • Non-local variable
    Non-local variable
    In programming language theory, a non-local variable is a variable that is not defined in the local scope. While the term can refer to global variables, it is primarily used in the context of nested and anonymous functions where some variables can be neither in the local nor the global scope.-...

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK