HOME

TheInfoList



OR:

In
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, a global variable is a variable with global
scope Scope or scopes may refer to: People with the surname * Jamie Scope (born 1986), English footballer * John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution Arts, media, and entertainment * Cinem ...
, meaning that it is visible (hence accessible) throughout the program, unless
shadowed ''Shadowed'', also known as ''The Gloved Hand'', is a 1946 American film noir crime film directed by John Sturges and starring Anita Louise, Lloyd Corrigan, and Robert Scott. Plot Salesman Fred J. Johnson manages to hit a hole-in-one as he p ...
. The set of all global variables is known as the ''global environment'' or ''global state.'' In
compiled languages A compiled language is a programming language whose implementations are typically compilers (translators that generate machine code from source code), and not interpreters (step-by-step executors of source code, where no pre-runtime translati ...
, global variables are generally
static variable In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
s, whose extent (lifetime) is the entire runtime of the program, though in interpreted languages (including
command-line interpreter A command-line interpreter or command-line processor uses a command-line interface (CLI) to receive commands from a user in the form of lines of text. This provides a means of setting parameters for the environment, invoking executables and pro ...
s), 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 In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts o ...
, 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 Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired function ...
languages that enforce a module structure, or
class-based Class-based programming, or more commonly class-orientation, is a style of object-oriented programming (OOP) in which inheritance (object-oriented programming), inheritance occurs via defining ''class (computer programming), classes'' of object ...
object-oriented programming language Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of pro ...
s that enforce a class structure.


Use

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 Local may refer to: Geography and transportation * Local (train), a train serving local traffic demand * Local, Missouri, a community in the United States * Local government, a form of public administration, usually the lowest tier of administrat ...
with no
shared memory In computer science, shared memory is memory that may be simultaneously accessed by multiple programs with an intent to provide communication among them or avoid redundant copies. Shared memory is an efficient means of passing data between progr ...
(and therefore all interactions can be reconducted to
message passing In computer science, message passing is a technique for invoking behavior (i.e., running a program) on a computer. The invoking program sends a message to a process (which may be an actor or object) and relies on that process and its supporting i ...
). 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 In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified. Namespaces ...
though some problems may persist without proper encapsulation. Without proper locking (such as with a
mutex In computer science, a lock or mutex (from mutual exclusion) is a synchronization primitive: a mechanism that enforces limits on access to a resource when there are many threads of execution. A lock is designed to enforce a mutual exclusion concur ...
), code using global variables will not be
thread-safe Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without uni ...
except for read only values in
protected memory Memory protection is a way to control memory access rights on a computer, and is a part of most modern instruction set architectures and operating systems. The main purpose of memory protection is to prevent a process from accessing memory that ha ...
.


Environment variables

Environment variables An environment variable is a dynamic-named value that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs. For example, a running process can query the value of the TEMP envi ...
are a facility provided by some
operating systems An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. Time-sharing operating systems schedule tasks for efficient use of the system and may also inc ...
. Within the OS's
shell Shell may refer to: Architecture and design * Shell (structure), a thin structure ** Concrete shell, a thin shell of concrete, usually with no interior columns or exterior buttresses ** Thin-shell structure Science Biology * Seashell, a hard o ...
( ksh in
Unix Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and ot ...
,
bash Bash or BASH may refer to: Arts and entertainment * ''Bash!'' (Rockapella album), 1992 * ''Bash!'' (Dave Bailey album), 1961 * '' Bash: Latter-Day Plays'', a dramatic triptych * ''BASH!'' (role-playing game), a 2005 superhero game * "Bash" ('' ...
in
Linux Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which ...
,
COMMAND.COM COMMAND.COM is the default command-line interpreter for MS-DOS, Windows 95, Windows 98 and Windows Me. In the case of DOS, it is the default user interface as well. It has an additional role as the usual first program run after boot (init proc ...
in
DOS DOS is shorthand for the MS-DOS and IBM PC DOS family of operating systems. DOS may also refer to: Computing * Data over signalling (DoS), multiplexing data onto a signalling channel * Denial-of-service attack (DoS), an attack on a communicat ...
and
CMD.EXE Command Prompt, also known as cmd.exe or cmd, is the default command-line interpreter for the OS/2, eComStation, ArcaOS, Microsoft Windows (Windows NT family and Windows CE family), and ReactOS operating systems. On Windows CE .NET 4.2, Windo ...
in
Windows Windows is a group of several proprietary graphical operating system families developed and marketed by Microsoft. Each family caters to a certain sector of the computing industry. For example, Windows NT for consumers, Windows Server for serv ...
) they are a kind of variable: for instance, in unix and related systems an ordinary variable becomes an environment variable when the export keyword is used. Program code other than shells has to access them by
API An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software Interface (computing), interface, offering a service to other pieces of software. A document or standa ...
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
fork In cutlery or kitchenware, a fork (from la, furca 'pitchfork') is a utensil, now usually made of metal, whose long handle terminates in a head that branches into several narrow and often slightly curved tines with which one can spear foods ei ...
ing, 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.


Global-only and global-by-default

A number of non-
structured Structuring, also known as smurfing in banking jargon, is the practice of executing financial transactions such as making bank deposits in a specific pattern, calculated to avoid triggering financial institutions to file reports required by law ...
languages, such as (early versions of)
BASIC BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
,
COBOL COBOL (; an acronym for "common business-oriented language") is a compiled English-like computer programming language designed for business use. It is an imperative, procedural and, since 2002, object-oriented language. COBOL is primarily us ...
and Fortran I (1956) only provide global variables. Fortran II (1958) introduced subroutines with local variables, and the COMMON keyword for accessing global variables. Usage of COMMON in FORTRAN continued in FORTRAN 77, and influenced later languages such as PL/SQL. Named COMMON groups for globals behave somewhat like structured namespaces. Variables are also global by default in
Forth Forth or FORTH may refer to: Arts and entertainment * ''forth'' magazine, an Internet magazine * ''Forth'' (album), by The Verve, 2008 * ''Forth'', a 2011 album by Proto-Kaw * Radio Forth, a group of independent local radio stations in Scotla ...
,
Lua Lua or LUA may refer to: Science and technology * Lua (programming language) * Latvia University of Agriculture * Last universal ancestor, in evolution Ethnicity and language * Lua people, of Laos * Lawa people, of Thailand sometimes referred t ...
,
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offici ...
, and most shells.


By language


C and C++

The C language does not have a global
keyword Keyword may refer to: Computing * Keyword (Internet search), a word or phrase typically used by bloggers or online content creator to rank a web page on a particular topic * Index term, a term used as a keyword to documents in an information syst ...
. However, variables declared outside a function have "file scope," meaning they are visible within the file. Variables declared with file scope are visible between their declaration and the end of the compilation unit (.c file) (unless shadowed by a like-named object in a nearer scope, such as a local variable); and they implicitly have external linkage and are thus visible to not only the .c file or
compilation unit In C and C++ programming language terminology, a translation unit (or more casually a compilation unit) is the ultimate input to a C or C++ compiler from which an object file is generated. A translation unit roughly consists of a source file aft ...
containing their declarations but also to every other compilation unit that is linked to form the complete program. External linkage, however, is not sufficient for such a variable's use in other files: for a compilation unit to correctly access such a global variable, it will need to know its type. This is accomplished by declaring the variable in each file using the extern keyword. (It will be ''declared'' in each file but may be ''defined'' in only one.) Such extern declarations are often placed 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 (or linking) error. An example of a "global" variable in C: #include // This is the file-scope variable (with internal linkage), visible only in // this compilation unit. static int shared = 3; // This one has external linkage (not limited to this compilation unit). extern int over_shared; // Also internal linkage. int over_shared_too = 2; static void ChangeShared() static void LocalShadow() static void ParamShadow(int shared) int main() 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 5 5


Java

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 (also known as
class variable In class-based, object-oriented programming, a class variable is a variable defined in a class of which a single copy exists, regardless of how many instances of the class exist. A class variable is not an instance variable. It is a special typ ...
s) exist independently of any instances of the class and one copy is shared among all instances; hence public static fields are used for many of the same purposes as global variables in other languages because of their similar "sharing" behavior: public class Global


PHP

PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group ...
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.


Other languages

* In
Python Python may refer to: Snakes * Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia ** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia * Python (mythology), a mythical serpent Computing * Python (pro ...
and
MATLAB MATLAB (an abbreviation of "MATrix LABoratory") is a proprietary multi-paradigm programming language and numeric computing environment developed by MathWorks. MATLAB allows matrix manipulations, plotting of functions and data, implementation ...
a global variable can be declared anywhere with the global keyword. *
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sa ...
's global variables are distinguished by a '$'
sigil A sigil () is a type of symbol used in magic. The term has usually referred to a pictorial signature of a deity or spirit. In modern usage, especially in the context of chaos magic, sigil refers to a symbolic representation of the practitioner ...
. A number of predefined globals exist, for instance $$ is the current
process ID In computing, the process identifier (a.k.a. process ID or PID) is a number used by most operating system kernels—such as those of Unix, macOS and Windows—to uniquely identify an active process. This number may be used as a parameter in various ...
.


See also

*
Local variable In computer science, a local variable is a Variable (programming), variable that is given ''local scope (programming), scope''. A local variable reference in the subroutine, function or block (programming), block in which it is declared overrides ...
*
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 ...
*
Singleton pattern In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. One of the well-known "Gang of Four" design patterns, which describe how to solve recurring problems ...
* Variables **
Static variable In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
**
External variable In the C programming language, an external variable is a variable defined outside any function block. On the other hand, a local (automatic) variable is a variable defined inside a function block. Definition, declaration and the extern keywor ...


References

{{reflist Variable (computer science) de:Variable (Programmierung)#Variablen in einer Blockstruktur