Skip to content
Definition
Variable scope determines where a variable can be accessed within a program. Local variables are restricted to their block/subroutine, while global variables are accessible throughout the entire program.

Local Variables

Key Point
Scope typeWhere accessibleStrengthsRisks
Local variableOnly inside defining block/subroutineEncapsulation, safer changes, better memory lifecycleNot directly shareable outside scope
Global variableAcross whole programConvenient shared stateHidden dependencies, accidental overwrite, harder debugging
Worked Example
Scope Example
pseudocode
// 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()
Best Practice: Minimise global variables. Pass data via parameters instead.

Variables, Constants and Identifiers

Definition
A variable is a named location in memory that stores a value which can change while the program is running. Its name is its identifier. A constant is a named value that cannot change while the program is running.
  • •
    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