A local variable can be accessed only within the subprogram or block where it is declared, whereas a global variable can be accessed by multiple parts of the program. Scope therefore determines where an identifier is visible and may be used.
How Scope Works
Scope is the region of a program in which a variable or other identifier can be referenced. When a subprogram is called, its local variables are created for that execution; they normally cease to exist when the subprogram finishes.
A global variable is declared outside subprograms and remains available throughout the program, subject to the rules of the programming language. Changes made to a global variable can therefore affect other subprograms that use it.
| Feature | Local scope | Global scope |
|---|---|---|
| Declaration | Inside a subprogram or block | Outside subprograms |
| Accessibility | Only within its declaring region | Across multiple parts of the program |
| Typical use | Parameters, counters and temporary results | Shared program-wide data |
| Main advantage | Reduces unintended interference | Allows data sharing between subprograms |
| Main risk | Unavailable outside its scope | Unexpected changes and harder debugging |
Consider this pseudocode:
score = 10
FUNCTION addBonus(bonus)
newScore = score + bonus
RETURN newScore
END FUNCTION
Here, score has global scope, so addBonus can access it. The parameter bonus and variable newScore have local scope, so code outside addBonus cannot access them.
If a local variable has the same name as a global variable, shadowing may occur: references inside the local scope use the local variable rather than the global one.
A common misconception is that scope and lifetime are identical. Scope concerns where a variable is accessible; lifetime concerns how long it exists during program execution.
Exam Technique
For IB Computer Science B2.3 questions, identify where each variable is declared, state where it can be accessed, and explain the consequence. When evaluating program design, note that local variables support modularity and reduce side effects, while excessive use of global variables can make programs harder to test, trace and maintain.