A global variable in programming is a variable whose scope is the entire program, except for specially . Mechanisms of interaction with global variables are called mechanisms of access to the global environment or state ( eng. Global environment , global state ). Global variables can be used for interaction between procedures and functions as an alternative to passing arguments and returning values [1] .
The use of global variables has drawbacks: a global variable can be changed at any point in the program (if it is not in protected memory or declared as a - variable, which can affect the operation of other parts of the program [2] . For this reason, global variables have unlimited potential for creating mutual dependencies, which makes the program more complex, however in some cases it is useful to use global variables. For example, they can be used to select There is no need to pass frequently used variables through several functions.Global variables also make it difficult to integrate modules , since the code written earlier may contain global variables with the same names as in the plug-in module.
Global variables are widely used to transfer data between sections of code that are not involved in call relationships, such as parallel execution threads or signal handlers . Without proper locking (for example, using a mutex ), code that uses global variables will not be thread-safe , except for variables that are read-only in a protected area of memory . With an increase in the number of variables and, accordingly, locks , the likelihood of interlocks increases.
C example:
int a ; / * Declaration of a global integer variable "a" * /
float b = 6 ; / * Declaring a global variable floating point “b” and assigning it the value “6” * /
int main ( void )
{
a = 12 ; / * Assigning variable “a” to “12” * /
return a + b ;
}
Notes
- ↑ Kernighan and Ritchie . C programming language - p. 44, 87.
- ↑ William Wulf and Mary Shaw, Global Variable Considered Harmful, ACM SIGPLAN Notices, volume 8, issue 2, 1973 February, pp. 28-34.