Constants and variables

In a program, data values can be constant or variable. If values are variable they can be changed by the program and the user.

When a program is run, the data values are held in memory whilst they are being worked on.

Constants

Data values that stay the same every time a program is executed are known as constants. Constants are not expected to change.

Literal constants are actual values fixed into the source code. An example of this might be the character string "hello world". The data value "hello world" has been fixed into the code.

Named constants are values where a name is defined to be used instead of a literal constant. An example of this might be stating that the 'starting level' of a game is always referred to as 1.

Examples of a constant within a game might be:

  • the unit of gravity
  • the number of lives available for the player
  • the amount of time allowed for a level in a game

Variables

Variables are data values that can change when the user is asked a question, for example, their age. Variables may change during program execution.

A variable is a memory location. It has a name that is associated with that location. The memory location is used to hold data. The key difference when comparing a constant to a variable is that the value associated with a variable name may change during program execution. For example 'highScore' would need to be variable to change throughout a game.

Diagram demonstrating a Boolean algorithm

The content and organisation of a computer's memory is not fixed - so neither is the value that is pointed at by a variable.

When data is read from a variable, the content of the memory location is copied and used in calculations.