Cambridge O Level Computer Science · Syllabus 2210 · Programming
Local Variable
What is Local Variable?
A variable declared inside a procedure or function, available only within that routine; it cannot be read or changed from anywhere else in the program.
This definition is part of the Programming chapter in Cambridge O Level Computer Science.
Local 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.
Common mistakes with Local Variable
- M19. “A local variable can be used anywhere in the program.” TruthA local variable is declared inside a procedure or function and is available only within that routine. Elsewhere the identifier refers to nothing. AlsoTwo routines cannot see each other's locals, and a local with the same name as a global is a different store.
Questions students ask about Local 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.

