Proficient programming requires knowledge of many techniques. These techniques allow for powerful, complex programs to be created.
Programs usually use data in some shape or form. Data is often stored within a program using variables and constants.
A variable is a named piece of memory that holds a value. The value held in a variable can - and usually does - change as the program is running.
A variable's name is known as an identifier. The identifier given to a variable usually follows certain rules known as a naming convention:
Acceptable identifiers | Unacceptable identifiers |
---|---|
highScore | high score |
high_score | 123score |
highScore123 | $core |
Variables make it easy for a programmer to use memory locations. The computer keeps track of which memory location the variable refers to. All the programmer has to do is remember the identifier the variable was given.
Most programming languages require a variable to be identified before a value is assigned to it. This is known as declaring a variable. In Visual Basic, this would look like:
Dim score as Integer
- would declare a variable called score
which will hold integers.
Giving a variable a value is known as assignment. For example, giving the variable above a value would look like the following in Visual Basic:
score = 0
- would assign the value 0 to the variable score
Some programming languages, such as Python, do not require variables to be explicitly declared before use.
A constant is a named piece of memory where the value cannot be changed while a program runs.
Constants are useful because they are declared and assigned once, but can be referred to over and over again throughout the program. This means that if the programmer needs to change the value throughout the program code, they only need to make one change. This can help make a program easier to maintain.
Constants follow the same naming conventions as variables, except that they are often written in uppercase. Some programming languages, such as Python, do not support constants.
Constants are used for values that are unlikely to change, for example:
Pi - PI ← 3.142
A global variable is one that can be accessed and changed throughout the whole program. Local variables only exist within a particular subroutine.
Using local variables rather than global variables makes it easier to debug a program as the value of that variable can only be read or changed within one subroutine. Another advantage of local variables is memory efficiency. Once a subroutine has finished running, the memory used for all local variables is removed.
In general, the use of global variables should be avoided wherever possible.