A variable is a named data storage location in memory. Using variables a computer program can store numbers, textual data, binary-data, or a combination of any of these data types. The data can be passed around in a program by copying it from variable to variable or by referencing variables, i.e. defining from which variable a receiving code part is to take the contained data.
Variables which are only accessible within a certain function are termed "local variables". A "global variable", or one with indefinite scope, may be referred to anywhere in the program.
In some programming-languages, variables are constrained by a specific data type. Data types may vary across languages, but share many commonalities.
Primitive data types usually include:
- character, char, string, varchar (text)
- byte, short, int, tinyint, integer, long (whole numbers)
- double, decimal, float (real numbers)
- bit, boolean (true/false)
- date, datetime (date and time values)
- object (any value, including composite types)
- binary, raw, varbinary (that store stream of system data in binary form)
Composite data types consist of usually more than one of the primitive types and/or even other composite types.
# an example composite type, in pseudo code Person( 'First name' : string, 'Surname' : string, 'Birthday' : date, 'CanProgram' : boolean )
Some languages contain extra primitives: Tuples (Python), Linked Lists (Lisp), Hash Tables (Lisp, Perl, Python, Lua, D).
Some programming languages allow variables that store functions, that can be stored in data structures, passed as parameters to other functions, or returned as a result from other functions.
The specifics of variable allocation and the representation of their values vary widely, both among programming languages and among implementations of a given language. Many language implementations allocate space for local variables (whose extent lasts for a single function call) on the stack, and their memory is automatically reclaimed when the function returns. More generally, in name binding, the name of a variable is bound to the address of some particular block (contiguous sequence) of bytes in memory, and operations on the variable manipulate that block. Referencing is more common for variables whose values have large or unknown sizes when the code is compiled. Such variables reference the location of the value instead of storing the value itself, which is allocated from a pool of memory called the heap.
More information and reference material on Wikipedia.