Global variable

From Wikipedia, the free encyclopedia

In computer programming, a global variable is a variable that does not belong to any subroutine or class and can be accessed from anywhere in a program. They are contrasted with local variables. See also scope.

They are usually considered bad practice precisely because of their nonlocality: a global variable can potentially be modified from anywhere, 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. They can be used to avoid having to pass frequently-used variables continuously throughout several functions, for example.

Global variables are used extensively to pass informations 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 thought some problems may persist without proper encapsulation. Without proper locking (ex. with a mutex), code using global variables will usually not be thread-safe.

[edit] See also


In other languages