Constants and Variables

All elements of data used in a program are given identifiers (names) to distinguish between them.

These elements of data have values, and may be one of two types:

  • constants - the value remains the same every time the program is run, and does not change throughout the running of the program.

  • variables - the value may change.

In programming, all variables and constants must be declared. When a declaration is made, the computer reserves space in memory for storing its value, and labels this space with the identifier.

 

Each programming language has its own rules about the naming of identifiers.

Eg. It must start with a Letter and have no spaces.

The scope of a variable (or constant) is the section of program where a variable's value may be accessed and used.

Global variables exist throughout the run of a program. They are declared at the start of a program and values may be accessed at any time during the run of the program.

Local variables are declared in a subroutine or function. They are created when the subroutine is started  and only exist for the time the subroutine is run. When the subroutine is completed the memory space reserved for local variables is released for other use.

Note : It is important that variables and constants should be declared locally if possible. This saves memory space when programs are run.