What Does Global Variable Mean?
A global variable is a programming language construct, a variable type that is declared outside any function and is accessible to all functions throughout the program. A group of global variables is called a global state or global environment because when combined, they define various aspects of a program or the environment when the program runs. A global variable is usually declared on top of all functions and is kept to a minimum, as all functions can manipulate them during the program’s run time, which is considered dangerous by most programmers because they may accidentally be changed, resulting in bugs.
Techopedia Explains Global Variable
Global variables, as the name implies, are variables that are accessible globally, or everywhere throughout the program. Once declared, they remain in memory throughout the runtime of the program. This means that they can be changed by any function at any point and may affect the program as a whole. During the early years of computers where memory was very limited, they became considered bad practice because they took up valuable memory space and it was very easy for the programmer to lose track of their values, especially in long programs, leading to bugs that can be very hard to locate. Source code is best understood when the scope of its individual elements are limited, so because of their non-locality, it is hard to keep track of where they have been changed or why they were changed.
Even with this stigma, global variables are valuable in functions that do not share a ‘’caller and callee” relation, such as signal handlers and concurrent threads. With the exception of global variables declared as read only values in protected memory, codes should deploy proper encapsulation in order to be considered “thread-safe.”
Early versions of non-structured languages like BASIC, COBOL and Fortran only used global variables. However languages like Lua, Forth and Perl use global variables by default as do most shell scripts.