A global variable can be accessed from multiple parts of a program, whereas a local variable can be accessed only within the subprogram or block where it is declared. The central difference is therefore the variable's scope.
Scope and Lifetime
Scope describes the part of a program in which an identifier can be referenced. A global variable is normally declared outside all subprograms, while a local variable is declared inside a procedure, function, method, or block.
Lifetime describes how long the variable exists during program execution. A global variable usually exists throughout the program's execution. A local variable normally exists only while its subprogram is executing, although exact lifetime rules depend on the programming language.
| Feature | Global variable | Local variable |
|---|---|---|
| Declaration | Outside subprograms | Inside a subprogram or block |
| Scope | Available across much or all of the program | Available only within its declaring scope |
| Typical lifetime | Entire program execution | One subprogram call or block execution |
| Main risk | Unintended changes from different program sections | Inaccessible outside its scope |
| Appropriate use | Shared program state or constants | Temporary calculations and parameters |
Consider this simplified pseudocode:
GLOBAL score
score = 0
PROCEDURE addPoint()
LOCAL points
points = 1
score = score + points
END PROCEDURE
Here, score is global because addPoint and other program sections may access it. points is local: it is available only inside addPoint and cannot be referenced after that procedure finishes.
A common misconception is that a local variable must have a unique name throughout the program. In many languages, a local variable may have the same name as a global variable; the local declaration then the global variable within that scope.