Variable Scope, Knowledge Organiser

Knowledge Organiser: Variable Scope

Key Terms

  • Scope: The region of code where a variable can be seen and used
  • Local variable: Declared inside a subprogram; accessible only within that subprogram
  • Global variable: Declared outside all subprograms; accessible anywhere in the program
  • Lifetime: How long a variable exists — local variables are created when the function runs and destroyed when it ends

Must-Know Facts

  • Local variables cannot be accessed outside the subprogram they are declared in
  • Global variables exist for the entire runtime of the program
  • Local variables are more memory-efficient — they are freed when the function ends
  • Parameters are local to the function they belong to
  • Best practice: use local variables wherever possible — safer and tidier
  • Accessing a local variable outside its function causes a runtime error

Key Concepts

  • Declare global: global score = 0
  • Declare local: local bonus = 10 inside a function
  • Global can be read and modified from any subprogram
  • Local is created on function call, destroyed on function return

Common Mistakes

  • Trying to use a local variable outside its function: Local variables only exist inside the subprogram where they are declared — accessing them elsewhere causes a runtime error
  • Assuming global variables are always better: Global variables can be accidentally modified by any part of the program — local variables are safer and preferred where possible
  • Forgetting local variables are destroyed after function ends: Local variables do not retain their value between function calls — a new copy is created each time the function runs
  • Confusing scope with data type: Scope (local/global) describes WHERE a variable is accessible; data type (integer/string) describes WHAT it stores — these are separate concepts

PrepWise is a trading name of A3M Quality Solutions Limited, registered in England and Wales, company number 14959172. Registered office: 202 Stroud Road, Gloucester, GL1 5LA. ICO registration ZC267069.