Global Variable

Why Trust Techopedia

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.

Advertisements

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.

Advertisements

Related Terms

Margaret Rouse
Technology expert
Margaret Rouse
Technology expert

Margaret is an award-winning writer and educator known for her ability to explain complex technical topics to a non-technical business audience. Over the past twenty years, her IT definitions have been published by Que in an encyclopedia of technology terms and cited in articles in the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine, and Discovery Magazine. She joined Techopedia in 2011. Margaret’s idea of ​​a fun day is to help IT and business professionals to learn to speak each other’s highly specialized languages.