Cambridge O Level Computer Science · Syllabus 2210 · Programming
Global Variable
What is Global Variable?
A variable declared outside all procedures and functions, available throughout the program including inside routines; convenient but easy to change by accident from anywhere.
This definition is part of the Programming chapter in Cambridge O Level Computer Science.
Global Variable in context
A local variable is declared inside a procedure or function and is available only within that routine. A global variable is declared outside all routines and is available throughout the program, including inside the routines. A routine's parameters behave as local variables too. Local variables are preferred because they cannot be changed by accident from somewhere else in the program, which makes a routine easier to test on its own; too many globals make a program harder to understand, harder to test and harder to change safely.
Questions students ask about Global Variable
Why are local variables generally preferred over global variables?
A local variable is declared inside a procedure or function and is available only within that routine, so it cannot be changed by accident from anywhere else in the program, which makes the routine easier to test on its own. A global variable is declared outside all routines and is available throughout the program, including inside every routine, so any routine can change it — when a global holds the wrong value, every routine that touches it becomes a suspect, and none can be tested in isolation.

