Scoping

From Higher Computing Science
Revision as of 13:31, 10 June 2015 by Admin (Talk | contribs) (Information)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This article is unfinished. Please consider joining and adding to this article. Read about Page layout beforehand.

Key points

  • Variables declared within a subprogram will be local variables. This means that they only exist during the lifetime of the subprogram’s execution.
  • Variables declared outside of subprograms will be global variables. This means they are accessible from any part of the program.
  • Global variables can be dangerous for programmers – a variable with global scope can be seen by the whole program. A global variable with a common name such as total or name may “overlap” with a local variable elsewhere. This could cause confusion.


Information

Variables have scope, which means that they may be used by the whole program or just certain subprograms within a program.

Scoping is important because it limits the use of variables to the area of code that they are relevant. This makes code safer, because variables cannot be mistakenly used in the wrong area of a program.

Local variables have a scope that extends to the subroutine they are declared in. Outside of this subroutine, they are not visible.

Global variables have a scope that extends to the whole of a program.

The video and code examples below give examples of local and global variables.


Videos

Further information

Test yourself

Teaching resources