VARIABLE SCOPE
Higher Computing Science
LOCAL VARIABLES
• Declared within the sub-program
• Only recognised in the sub-program in which the variable is declared
• Can only be changed by code in the sub-program in which the variable
is declared
GLOBAL VARIABLES
• Declared as global in the main program
• Can be recognised and changed by any code in the entire program
• Should be avoided, especially with large programs
• Hard to keep track of which code updates the global variable
• Makes code more difficult to read
• Logic errors caused by code unexpectedly changing the value of a global
variable, and harder to debug
VARIABLE SCOPE
• Local variable scope: the sub-program in which it is declared
• Global variable scope: the entire program

Variable Scope

  • 1.
  • 2.
    LOCAL VARIABLES • Declaredwithin the sub-program • Only recognised in the sub-program in which the variable is declared • Can only be changed by code in the sub-program in which the variable is declared
  • 3.
    GLOBAL VARIABLES • Declaredas global in the main program • Can be recognised and changed by any code in the entire program • Should be avoided, especially with large programs • Hard to keep track of which code updates the global variable • Makes code more difficult to read • Logic errors caused by code unexpectedly changing the value of a global variable, and harder to debug
  • 4.
    VARIABLE SCOPE • Localvariable scope: the sub-program in which it is declared • Global variable scope: the entire program