Local Variables
| Scope type | Where accessible | Strengths | Risks |
|---|---|---|---|
| Local variable | Only inside defining block/subroutine | Encapsulation, safer changes, better memory lifecycle | Not directly shareable outside scope |
| Global variable | Across whole program | Convenient shared state | Hidden dependencies, accidental overwrite, harder debugging |
// Global variable
global MAX_SIZE = 100
procedure example():
// Local variable
local count = 0
count = count + 1
print(count) // Works: prints 1
print(MAX_SIZE) // Works: accesses global
end procedure
// Main program
example()
print(MAX_SIZE) // Works: prints 100
print(count) // ERROR! count is local to example()
Variables, Constants and Identifiers
- •A local variable is created when its subroutine is called and removed from memory when the subroutine ends
- •A global variable stays in memory for the whole time the program is running
- •If a subroutine declares a local variable with the same identifier as a global variable, the local one is used inside that subroutine and the global variable is left unchanged