成人论坛

Variables

Variables are used to identify storage locations in RAM (main memory) that will store the values used by a program.

When a variable is declared, a storage location is allocated in RAM. Programmers create a name for a variable so that they can reference the storage location and use the value held there throughout the source code.

When programming, the programmer will give each variable its own identifier or name.

DECLARE score INITIALLY 0

The line above creates a variable called score and sets its initial value to 0. Even though the programmer does not see anything happen, the computer will set a location in memory aside to store the value 0. Anytime the programmer uses the variable name 鈥荣肠辞谤别鈥 the computer will know to go back to that memory location to find the value.

Sometimes it is necessary to also include the data type when declaring a variable. The same variable could be declared as:

DECLARE score AS INTEGER INITIALLY 0

This lets the computer know that the data type is integer, meaning that whole numbers will be stored within the score variable. Some languages expect programmers to state data types while others set the data type automatically once the values are entered.

It is important to give variables meaningful and relevant names so that we can understand and remember their purpose. For example, we can quickly understand what a variable called 'score' means, but 's' on its own might not be as easy for us to understand or remember.

Assigning a value to a variable

When variables are declared they are usually given an initial value, like the value 0 in the example above. It is also possible to assign values to variables when a program is running.

SET score TO score + 1

The code above is an example of assignment. The programmer has assigned a new value to the score variable. In this case, they have added 1 onto the score. As the score started at 0 it would now be 1. The value in memory would change from 0 to 1.

There are different types of data that can be stored in memory. In the above example we have used the integer data type, but for more information, go to the section of this guide on Data types and structures.