Temporary variable
From Wikipedia, the free encyclopedia
In computer programming, a temporary variable is a variable whose purpose is short-lived, usually to hold temporarily data that will soon be discarded, or before it can be placed at a more permanent memory location. Because it is short-lived, it is usually declared with local scope. There is no formal definition of what makes a variable temporary, but it is an often–used term in programming.
A typical example would be that of swapping the contents of two variables. To swap the contents of variables a and b one would typically use a temporary variable temp as follows, so as to preserve the data from a as it is being overwritten by b:
temp := a a := b b := temp
A more real example is that of swapping two elements in an array, as is done in the RC4 algorithm and in sorting algorithms.
As a variable may be allocated to limited machine resources (such as a register), it may be desirable to find ways to swap variables without the use of a temporary. One approach is to use exclusive or (XOR) operations:
a := a XOR b b := b XOR a a := a XOR b
Swapping is an important primitive for semaphores, in particular for multiprocessor systems. Many processors therefore include a swap instruction such as more recent Intel assembly's XCHG operation and ARM's SWP operation. Using these operations does not necessarily lead to a performance improvement, since similar swap processes have to be performed within the processor and access to shared memory must be controlled.
Temporary variables are usually named with identifiers that abbreviate the word temporary, such as temp, tmp or simply t, or with common metasyntactic variable names, the most common of which are foo, bar, baz (See also foobar).