Revise Computingrevisecomputing.co.uk
Free student revisionSee questionsFor schoolsSchool enquiry
Free revisionSee questionsFor schoolsSchool enquiry
Knowledge/A Level/H446/02 Algorithms and programming/Programming Techniques/Global and local variables

Global and local variables

Global and local variables.

2.2.1 Programming Techniques

Programming Techniques — Note 3 of 6

Candidates need to understand the difference, benefits and drawbacks of global and local variables. Candidates must be able to recognise where each is used and its impact on a program, for example the amount of memory used, and change a program from one to the other.

What you need to know

A variable's scope is the part of the program where it can be used. Global variables can be used anywhere; local variables only exist inside the subroutine where they are declared. Choosing the correct scope makes programs more reliable and easier to maintain.

What to know

  • Good practice: use local variables and pass data through parameters; keep global variables to a minimum.

Key terms

Global variable

Declared in the main program and accessible from anywhere in the program, including inside subroutines. In OCR pseudocode: global userid = 123.

  • Global variables: useful for values needed throughout the program (e.g. settings), but they can be changed accidentally anywhere, making bugs hard to find, and they use memory for the whole run.
Local variable

Declared inside a subroutine; it only exists while the subroutine runs and can only be accessed within it.

  • Local variables: memory is freed when the subroutine ends; the same name can be used in different subroutines without conflict; subroutines are self-contained and easier to reuse and test.
  • If a local variable has the same name as a global one, the local variable is used inside the subroutine.

Exam technique

  • Tip:Be able to change a program that uses global variables into one that uses local variables and parameters, and vice versa.

Programming Techniques

Note 3 of 6

  1. 1Programming constructs: sequence, iteration, branching
  2. 2Recursion, how it can be used and how it compares to an iterative approach
  3. 3Global and local variables
  4. 4Modularity, functions and procedures, parameter passing by value and by reference
  5. 5Use of an IDE to develop/debug a program
  6. 6Use of object oriented techniques
Topic overview
← Previous noteRecursion, how it can be used and how it compares to an iterative approach2.2.1 Programming TechniquesNext note →Modularity, functions and procedures, parameter passing by value and by reference2.2.1 Programming Techniques

Back to Programming Techniques