Log in / create account | Login with OpenID
DocForge
Programmer's Wiki

Variable

From DocForge

Variables in computer programming are analogous to variables in mathematics. In the computing context, variable identifiers typically consist of alphanumeric strings. These identifiers are then used to refer to values stored in computer memory. This convention of matching identifiers to values is one of several programmatic conventions for accessing values in computer memory.

Contents

[edit] Variable Naming Conventions

In some programming languages, specific characters (known as sigils) are prefixed or appended to variable identifiers to indicate the variable's type. For example:

  • In BASIC, the suffix $ on a variable name indicates that its value is a string.
  • In Perl, the sigils $, @, %, and & indicate scalar, array, hash, and subroutine variables, respectively.
  • In spreadsheets, variables can refer to cells (e.g. $A$2), named ranges, or values in associated source code or functions.

[edit] Variables in Source Code

In computer source code, a variable name is one way to bind a variable to a memory location; the corresponding value is stored as a data object in that location so that the object can be accessed and manipulated later via the variable's name.

[edit] Variables in Spreadsheets

In a spreadsheet, a cell may contain a formula with references to other cells. Such a cell reference is a kind of variable; its value is the value of the referenced cell.

[edit] Scope and Extent

The scope of a variable describes where in a program's text the variable may be used, while the extent (or lifetime) describes when in a program's execution a variable has a value. A variable's scope affects its extent.

Scope is a lexical aspect of a variable. Most programming languages define a specific scope for each variable, which may differ within a given program. The scope of a variable is the portion of the program code for which the variable's name has meaning and for which the variable is said to be "visible". Entrance into that scope typically begins a variable's lifetime and exit from that scope typically ends its lifetime. For instance, a variable with "lexical scope" is meaningful only within a certain block of statements or subroutine. A "global variable", or one with indefinite scope, may be referred to anywhere in the program. It is erroneous to refer to a variable where it is out of scope. Lexical analysis of a program can determine whether variables are used out of scope. In compiled languages, such analysis can be performed statically at compile time.

Extent, on the other hand, is a runtime (dynamic) aspect of a variable. Each binding of a variable to a value can have its own extent at runtime. The extent of the binding is the portion of the program's execution time during which the variable continues to refer to the same value or memory location. A running program may enter and leave a given extent many times, as in the case of a closure.

In portions of code, a variable in scope may never have been given a value, or its value may have been destroyed. Such variables are described as "out of extent" or "unbound". In many languages, it is an error to try to use the value of a variable when it is out of extent. In other languages, doing so may yield unpredictable results. Such a variable may, however, be assigned a new value, which gives it a new extent. By contrast, it is permissible for a variable binding to extend beyond its scope, as occurs in Lisp closures and C static variables. When execution passes back into the variable's scope, the variable may once again be used.

For space efficiency, a memory space needed for a variable may be allocated only when the variable is first used and freed when it is no longer needed. A variable is only needed when it is in scope, but beginning each variable's lifetime when it enters scope may give space to unused variables. To avoid wasting such space, compilers often warn programmers if a variable is declared but not used.

It is considered good programming practice to make the scope of variables as narrow as feasible so that different parts of a program do not accidentally interact with each other by modifying each other's variables. Doing so also prevents action at a distance. Common techniques for doing so are to have different sections of a program use different namespaces, or to make individual variables "private" through either dynamic variable scoping or lexical variable scoping.

Many programming languages employ a reserved value (often named "null" or "nil") to indicate an invalid or uninitialized variable.

[edit] Typed and Untyped Variables

In statically-typed languages such as Java or ML, a variable also has a "type", meaning that only values of a given class (or set of classes) can be stored in it. In dynamically-typed languages such as Python, it is values, not variables, which carry type. In Common Lisp, both situations exist simultaneously: a variable is given a type (if undeclared, it is assumed to be "T", the universal supertype) which exists at compile time. Values also have types, which can be checked and queried at runtime.

Typing of variables also allows polymorphisms to be resolved at compile time. However, this is different from the polymorphism used in object-oriented function calls (referred to as "virtual functions" in C++) which resolves the call based on the value type as opposed to the supertypes the variable is allowed to have.

Variables often store simple data like integers and literal strings, but some programming languages allow a variable to store values of other datatypes as well. Such languages may also enable functions to be parametric polymorphic. These functions operate like variables to represent data of multiple types. For example, a function named "length" may determine the length of a list. Such a length function may be parametric polymorphic by including a type variable in its type signature, since the amount of elements in the list is independent of the elements' types.

[edit] Parameters

The "arguments" or "formal parameters" of functions are also referred to as variables. For instance, in these equivalent functions in Python and Lisp,

def addtwo(x):
    return x + 2
(defun addtwo (x) (+ x 2))

the variable named x is an "argument" because it is given a value when the function is called. In most languages, function arguments have local scope. This specific variable named x can only be referred to within the addtwo function (though of course other functions can also have variables called x).

[edit] Memory allocation

The specifics of variable allocation and the representation of their values vary among programming languages and implementations of each language. Many programming language implementations allocate space for "local variables", whose extent lasts for a single function call on the "call stack", and whose memory is automatically reclaimed when the function returns. 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 the storing value itself, which is allocated from a pool of memory called the "heap".

Bound variables have values. A value, however, is an abstraction. In implementation, a value is represented by some "data object", which is stored somewhere in computer memory. The program, or the runtime environment, must set aside memory for each data object and, since memory is finite, ensure that this memory is yielded for reuse when the object is no longer needed to represent some variable's value.

Objects allocated from the heap must be reclaimed specially when the objects are no longer needed. In a garbage-collected language (such as C#, Java, and Lisp), the runtime environment automatically reclaims objects when extant variables can no longer refer to them. In non-garbage-collected languages, such as C, the program (and thus the programmer) must explicitly allocate memory, and then later free it, to reclaim its memory. Failure to do so leads to memory leaks, in which the heap is depleted as the program runs, risking eventual failure from exhausting available memory.

When a variable refers to a data structure created dynamically, some of its components may be only indirectly accessed through the variable. In such circumstances, garbage collectors (or analogous program features in languages that lack garbage collectors) must deal with a case where only a portion of the memory reachable from the variable needs to be reclaimed.

[edit] Constants

A constant variable is a variable whose value cannot be changed once it is initially bound to a value. In other words, constant variables cannot be assigned to. In purely functional programming, all variables are constant, because there is no assignment.

Although a constant value is specified only once, the constant variable can be referenced multiple times in a program. Using a constant instead of specifying a value multiple times in the program can not only simplify code maintenance, but it can also supply a meaningful name for it and consolidate such constant assignments to a standard code location (for example, at the beginning).

Programming languages provide one of two kinds of constant variables:

Static constant or Manifest constant
Languages such as Visual Basic allow assigning a fixed value to "static constant" which will be known at compile time. Such a constant has the same value each time its program runs. Changing the value is accomplished by changing (and possibly recompiling) the code. E.g.: CONST a = 60.
Dynamic constant
Languages such as C++ and Java allow initializing a "dynamic constant" with a value that is computed at runtime. Thus, unlike static constants, the values of dynamic constants cannot be determined at compile time. E.g.: final int a = b + 20;.

For variables which are references, do not confuse constant references with immutable objects. For example, when a non-constant reference references an immutable object, that reference can be changed so that it references a different object, but the object it originally pointed to cannot be changed (i.e. other references that reference it still see the same information).

Conversely, a constant reference may reference a mutable object. In this case, the reference will always reference the same object (the reference cannot be changed); however, the object that the reference references can still be changed (and other references that also reference that object will see the change), as shown in the following example:

final StringBuffer sampleDynamicConstant = new StringBuffer ("InitialValueOfDynamicConstant");
sampleDynamicConstant.append("_AppendedText");
System.out.println(sampleDynamicConstant);

The above code produces the following output:

InitialValueOfDynamicConstant_AppendedText

In languages where a variable can be an object (i.e. C++), such a variable being constant is equivalent to the immutability of that object.

[edit] Variable Interpolation

Variable interpolation (also variable substitution, variable expansion) is the process of evaluating an expression or string literal containing one or more variables, yielding a result in which the variables are replaced with their corresponding values in memory. It is a specialized instance of concatenation.

For example, the following Perl code:

$sName    = "Nancy";            
$sGreet   = "$sName said Hello World to the crowd of people.";
print  $sGreet;

produces the output:

   Nancy said Hello World to the crowd of people.


Additional copyright notice: Some content of this page is a derivative work of a Wikipedia article under the GNU FDL. The original article and author information can be found at http://en.wikipedia.org/wiki/Variable.