±«Óătv

Local and global variables

Sub-programs, functions, procedures and methods make use of variables.

can be declared as:

Global variables

A global variable places greater demand on system resources - it needs to be retained in memory (RAM) throughout the entire execution of a program.

This ensures that the value of the global variable is accessible to each part of the program at all times.

Errors in code can leave the value itself susceptible to accidental or unintentional change that can have a knock on effect elsewhere in the program.

In real terms and in real commercial programs there may be hundreds or thousands of variables in use during the execution of a program so this can be a major problem.

Local variables

A local variable is declared within one specific sub-program of a larger main program.

During the execution of this sub-program, the values of local variables will be held in RAM.

Upon completion of the execution of this sub-program the variable is no longer retained in RAM. This is more efficient in terms of demands on system resources.

Scope of variables

The scope of a global variable is the entire program.

The scope of a local variable is the sub-program where it has been declared.

Related links