Programming · 4 question types
Past paper frequency (2018 to 2024)
This topic accounts for approximately 4% of your exam marks.
Writing and calling procedures/functions with parameters is tested in Paper 2.
The of a variable is where in the program that variable can be seen and used.
A variable's scope depends on where it is declared. Two common scopes:
A is one that is declared inside a (procedure or function). It only exists while that sub-program is running; once the sub-program returns, the local variable is destroyed.
Example:
PROCEDURE ShowDouble(Number : INTEGER)
DECLARE Doubled : INTEGER
Doubled ← Number * 2
OUTPUT Doubled
ENDPROCEDURE
CALL ShowDouble(7)
OUTPUT Doubled // ERROR: Doubled does not exist here
Doubled is local to ShowDouble. The main program cannot see it. As soon as the procedure ends, Doubled is forgotten.
A is one that is declared outside any sub-program, at the top level of the program. It is visible throughout the entire program, including inside sub-programs.
Example:
DECLARE Score : INTEGER
Score ← 0
PROCEDURE AddPoint
Score ← Score + 1 // can see the global Score
ENDPROCEDURE
CALL AddPoint
CALL AddPoint
OUTPUT Score // outputs 2
Score is declared at the top level, so any sub-program can read and update it.
Although global variables are convenient, using them too freely makes programs hard to maintain:
Best practice: use local variables by default, and use and return values to pass information between sub-programs. Reserve globals for genuinely shared state, such as a running total or a configuration setting.
| Feature | Local variable | Global variable |
|---|---|---|
| Where declared | Inside a sub-program (procedure or function) | Outside any sub-program (top level) |
| Visible from | Only inside the sub-program that declared it | Anywhere in the program |
| Lifetime | Created when the sub-program starts; destroyed when it ends | Lives for the whole program run |
Most scope mistakes show up in three patterns. Knowing the symptoms makes them easy to fix:
A quick rule of thumb: if a value is needed in only one block, declare it locally; if several sub-programs must share it, pass it as a parameter or return it. Reach for a global only when the value really is shared state for the whole program.
| Risk of accidental interference | Low: name clashes are local to the block | Higher: any code can change the value |
| Best for | Temporary calculations, loop counters, intermediate results | Shared state, configuration, totals across many sub-programs |
| Preferred style | Default choice | Use sparingly |