Scope decides where a variable exists. A local variable lives only inside its procedure, while a global variable is shared with the main program. Tracing scope means asking, at every line, which variables are available.
This lesson belongs to program structure and debugging. It builds on tracing functions and parameters.
How do you keep a scope table?
Beside your trace, list each variable with the place it exists. Add a row when a variable is declared and remove it when the procedure ends.
In this pseudocode, GLOBAL declares a variable outside any procedure and LOCAL declares one inside a procedure.
Worked example: bonus points
GLOBAL score = 10
PROCEDURE addBonus()
LOCAL bonus = 5
SET score = score + bonus
OUTPUT bonus
END PROCEDURE
addBonus()
addBonus()
OUTPUT score
| Step | score (global) | bonus (local) | Output |
|---|---|---|---|
| Start | 10 | does not exist | |
| Call 1 inside | 15 | 5 | 5 |
| Call 1 ends | 15 | gone | |
| Call 2 inside | 20 | 5 | 5 |
| Call 2 ends | 20 | gone | |
| Final output | 20 | does not exist | 20 |
The outputs are 5, 5 and then 20. Each call creates a fresh bonus that starts at 5, which is why it does not grow.
What mistake does this catch?
A student adds OUTPUT bonus after the two calls, expecting 10 because 5 was added twice. That line fails, because bonus no longer exists once the second call ends.
| Line in the caller | Result |
|---|---|
| OUTPUT score | 20, since global survives |
| OUTPUT bonus | Error, since local is gone |
Two ways to fix this: have the procedure RETURN the value and store it, or declare the variable as global on purpose. Choose the first unless the value genuinely belongs to the whole program.
Check yourself
Trace this and state the final output, then say whether the last line would work.
GLOBAL total = 0
PROCEDURE add(n)
SET total = total + n
END PROCEDURE
add(3)
add(5)
OUTPUT total
OUTPUT n
Answer
The parameter n is local to each call. After add(3), total = 3. After add(5), total = 8. OUTPUT total gives 8.
OUTPUT n fails, because n existed only during the calls and is not defined in the main program.
What to study next
Move on to structural faults in diagnosing a loop that terminates too early or never terminates. Practise with the restricted pseudocode trace trainer.
If you would like a teacher to check your scope tables, see online one-to-one Computer Science tuition.