Variable
<programming> A named memory location in which a program can store intermediate results and from which it can read it them. Each
programming language has different rules about how variables can be named, typed, and used.
Typically, a value is "assigned" to a variable in an
assignment statement.
The value is obtained by evaluating an expression and then stored in the variable.
For example, the assignment
x = y + 1
means "add one to y and store the result in x".
This may look like a mathematical equation but the mathematical equality is only true in the program until the value of x or y changes. Furthermore, statements like
x = x + 1
are common.
This means "add one to x", which only makes sense as a state changing operation, not as a mathematical equality.
The simplest form of variable corresponds to a single-
word of
memory or a
CPU register and an assignment to a
load or
store machine code operation.
A variable is usually defined to have a
type, which never changes, and which defines the set of values the variable can hold.
A type may specify a single ("atomic") value or a collection ("aggregate") of values of the same or different types.
A common aggregate type is the
array - a set of values, one of which can be selected by supplying a numerical
index.
Languages may be
untyped,
weakly typed,
strongly typed, or some combination.
Object-oriented programming languages extend this to
object types or classes.
A variable's
scope is the region of the program source within which it represents a certain thing.
Scoping rules are also highly language dependent but most serious languages support both local and global variables.
In a
functional programming language, a variable's value never changes and change of state is handled as recursion over lists of values.