HOME

TheInfoList




In
computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, generating algorithms, Profilin ...
, a variable or scalar is an abstract storage location paired with an associated
symbolic name
symbolic name
, which contains some known or unknown quantity of information referred to as a ''
value Value or values may refer to: * Value (ethics) it may be described as treating actions themselves as abstract objects, putting value to them ** Values (Western philosophy) expands the notion of value beyond that of ethics, but limited to Western s ...
''; or in simpler terms, a variable is a container for a particular set of bits or type of data (like integer, float, String etc...). A variable can eventually be associated with or identified by a
memory address In computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and experimentation of algorithmic processes and development of both computer hardware , hardware and softwa ...
. The variable name is the usual way to
reference Reference is a relationship between objects in which one object designates, or acts as a means by which to connect to or link to, another object. The first object in this relation is said to ''refer to'' the second object. It is called a ''name ...
the stored value, in addition to referring to the variable itself, depending on the context. This separation of name and content allows the name to be used independently of the exact information it represents. The identifier in computer
source code In computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and experimentation of algorithmic processes and development of both computer hardware , hardware and ...

source code
can be
bound Bound or bounds may refer to: Mathematics * Bound variable * Upper and lower bounds, observed limits of mathematical functions Geography *Bound Brook (Raritan River), a tributary of the Raritan River in New Jersey *Bound Brook, New Jersey, a borou ...
to a
value Value or values may refer to: * Value (ethics) it may be described as treating actions themselves as abstract objects, putting value to them ** Values (Western philosophy) expands the notion of value beyond that of ethics, but limited to Western s ...
during run time, and the value of the variable may thus change during the course of program execution. Variables in programming may not directly correspond to the concept of variables in mathematics. The latter is abstract, having no reference to a physical object such as storage location. The value of a computing variable is not necessarily part of an
equation In mathematics Mathematics (from Greek: ) includes the study of such topics as numbers ( and ), formulas and related structures (), shapes and spaces in which they are contained (), and quantities and their changes ( and ). There is no ge ...

equation
or
formula In , a formula is a concise way of expressing information symbolically, as in a mathematical formula or a . The informal use of the term ''formula'' in science refers to the . The plural of ''formula'' can be either ''formulas'' (from the mos ...

formula
as in mathematics. Variables in computer programming are frequently given long names to make them relatively descriptive of their use, whereas variables in mathematics often have terse, one- or two-character names for brevity in transcription and manipulation. A variable's storage location may be referenced by several different identifiers, a situation known as
aliasing In signal processing Signal processing is an electrical engineering subfield that focuses on analysing, modifying, and synthesizing signals such as audio signal processing, sound, image processing, images, and scientific measurements. Sig ...
. Assigning a value to the variable using one of the identifiers will change the value that can be accessed through the other identifiers.
Compilers In computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and experimentation of algorithm of an algorithm (Euclid's algorithm) for calculating the greatest com ...
have to replace variables' symbolic names with the actual locations of the data. While a variable's name, type, and location often remain fixed, the data stored in the location may be changed during program execution.


Actions on a variable

In
imperative Imperative may refer to: *Imperative mood, a grammatical mood (or mode) expressing commands, direct requests, and prohibitions *Imperative programming, a programming paradigm in computer science *Imperative logic *Imperative (film), ''Imperative'' ...
programming language A programming language is a formal language In logic, mathematics, computer science, and linguistics, a formal language consists of string (computer science), words whose symbol (formal), letters are taken from an alphabet (computer science) ...

programming language
s, values can generally be accessed or
changed Change or Changing may refer to: Alteration * Impermanence, a difference in a state of affairs at different points in time * Menopause, also referred to as "the change", the permanent cessation of the menstrual period * Metamorphosis, or change, ...
at any time. In
pure Pure may refer to: Computing * A pure function * A virtual function, pure virtual function * PureSystems, a family of computer systems introduced by IBM in 2012 * Pure Software, a company founded in 1991 by Reed Hastings to support the Purify too ...
functional Functional may refer to: * Movements in architecture: ** Functionalism (architecture) In architecture File:Plan d'exécution du second étage de l'hôtel de Brionne (dessin) De Cotte 2503c – Gallica 2011 (adjusted).jpg, upright=1.45, alt=Pl ...
and logic languages, variables are
bound Bound or bounds may refer to: Mathematics * Bound variable * Upper and lower bounds, observed limits of mathematical functions Geography *Bound Brook (Raritan River), a tributary of the Raritan River in New Jersey *Bound Brook, New Jersey, a borou ...
to expressions and keep a single value during their entire lifetime due to the requirements of
referential transparency Referential transparency and referential opacity are properties of parts of computer program A computer program is a collection of instructions that can be executed by a computer to perform a specific task. A computer program is usually wri ...
. In imperative languages, the same behavior is exhibited by (named)
constant Constant or The Constant may refer to: Mathematics * Constant (mathematics) In mathematics, the word constant can have multiple meanings. As an adjective, it refers to non-variance (i.e. unchanging with respect to some other Value (mathematics ...
s (symbolic constants), which are typically contrasted with (normal) variables. Depending on the
type system In programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various kinds of Input/output, output. Programming languages are used in computer programming to ...
of a programming language, variables may only be able to store a specified
data type In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Alg ...
(e.g.
integer An integer (from the Latin Latin (, or , ) is a classical language belonging to the Italic branch of the Indo-European languages. Latin was originally spoken in the area around Rome, known as Latium. Through the power of the Roman Re ...
or
string String or strings may refer to: *String (structure), a long flexible structure made from threads twisted together, which is used to tie, bind, or hang other objects Arts, entertainment, and media Films * Strings (1991 film), ''Strings'' (1991 fil ...
). Alternatively, a datatype may be associated only with the current value, allowing a single variable to store anything supported by the programming language. Variables are the containers for storing the values. Variables and scope: *
Automatic variable __NOTOC__ In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming involves tasks such as: analysis ...
s: Each local variable in a function comes into existence only when the function is called, and disappears when the function is exited. Such variables are known as automatic variables. * External variables: These are variables that are external to a function and can be accessed by name by any function. These variables remain in existence permanently; rather that appearing and disappearing as functions are called and exited, they retain their values even after the functions that set them have returned.


Identifiers referencing a variable

An identifier referencing a variable can be used to access the variable in order to read out the value, or alter the value, or edit other
attributes Attribute may refer to: * Attribute (philosophy), an extrinsic property of an object * Attribute (research), a characteristic of an object * Grammatical modifier, in natural languages * Attribute (computing), a specification that defines a propert ...
of the variable, such as access permission,
locks Lock may refer to: *Lock and key, a mechanical device used to secure items of importance. *Lock (water navigation), a device for boats to transit between different levels of water Arts, entertainment, and media *Lock (film), ''Lock'' (film), a ...
, semaphores, etc. For instance, a variable might be referenced by the identifier "" and the variable can contain the number 1956. If the same variable is referenced by the identifier "" as well, and if using this identifier "", the value of the variable is altered to 2009, then reading the value using the identifier "" will yield a result of 2009 and not 1956. If a variable is only referenced by a single identifier, that identifier can simply be called ''the name of the variable''; otherwise we can speak of it as ''one of the names of the variable''. For instance, in the previous example the identifier "" is a name of the variable in question, and "" is another name of the same variable.


Scope and extent

The '' scope'' of a variable describes where in a program's text the variable may be used, while the ''extent'' (also called ''lifetime'') of a variable describes when in a program's execution the variable has a (meaningful) value. The scope of a variable affects its extent. The scope of a variable is actually a property of the name of the variable, and the extent is a property of the storage location of the variable. These should not be confused with ''context'' (also called ''environment''), which is a property of the program, and varies by point in the program's text or execution—see
scope: an overview
scope: an overview
. Further,
object lifetime In object-oriented programming (OOP), the object lifetime (or life cycle) of an object is the time between an object's creation and its destruction. Rules for object lifetime vary significantly between languages, in some cases between implementat ...
may coincide with variable lifetime, but in many cases is not tied to it. ''Scope'' is an important part of the name resolution of a variable. Most languages define a specific ''scope'' for each variable (as well as any other named entity), which may differ within a given program. The scope of a variable is the portion of the program's text 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 (as it comes into context) and exit from that scope typically ends its lifetime (as it goes out of context). For instance, a variable with "
lexical scopeIn computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming involves tasks such as: analysis, generatin ...
" is meaningful only within a certain function/
subroutine In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, generat ...
, or more finely within a block of expressions/statements (accordingly with
function scopeIn computer programming, the scope of a name binding—an association of a name to an entity, such as a Variable (programming), variable—is the part of a Computer program, program where the name binding is valid, that is where the name can be used ...
or
block scopeIn computer programming, the scope of a name binding—an association of a name to an entity, such as a Variable (programming), variable—is the part of a Computer program, program where the name binding is valid, that is where the name can be used ...
); this is static resolution, performable at parse-time or compile-time. Alternatively, a variable with dynamic scope is resolved at run-time, based on a global binding stack that depends on the specific control flow. Variables only accessible within a certain functions are termed "
local variable In computer science, a local variable is a Variable (programming), variable that is given ''local scope (programming), scope''. Local variable references in the subroutine, function or block (programming), block in which it is declared override the ...
s". A "
global variable In computer programming Computer programming is the process of designing and building an executable In computing, executable code, an executable file, or an executable program, sometimes simply referred to as an executable or binary, causes ...
", or one with indefinite scope, may be referred to anywhere in the program. ''Extent'', on the other hand, is a runtime (
dynamic Dynamics (from Greek Greek may refer to: Greece Anything of, from, or related to Greece Greece ( el, Ελλάδα, , ), officially the Hellenic Republic, is a country located in Southeast Europe. Its population is approximately 10.7 million ...
) 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. Unless the programming language features
garbage collection Waste collection is a part of the process of waste management. It is the transfer of solid waste from the point of use and disposal to the point of list of waste treatment technologies, treatment or landfill. Waste collection also includes the ...
, a variable whose extent permanently outlasts its scope can result in a
memory leak In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of , , ...
, whereby the memory allocated for the variable can never be freed since the variable which would be used to reference it for deallocation purposes is no longer accessible. However, it can be permissible for a variable binding to extend beyond its scope, as occurs in Lisp closures and C
static local variable In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of , , a ...
s; when execution passes back into the variable's scope, the variable may once again be used. A variable whose scope begins before its extent does is said to be '' uninitialized'' and often has an undefined, arbitrary value if accessed (see
wild pointer Dangling pointers and wild pointers in computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming invo ...
), since it has yet to be explicitly given a particular value. A variable whose extent ends before its scope may become a
dangling pointer Dangling pointers and wild pointers in computer programming Computer programming is the process of designing and building an executable In computing, executable code, an executable file, or an executable program, sometimes simply referred ...
and deemed uninitialized once more since its value has been destroyed. Variables described by the previous two cases may be said to be ''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. 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, thus 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 In physics Physics is the that studies , its , its and behavior through , and the related entities of and . "Physical science is that department of knowledge which relates to the order of nature, or, in other words, to the regular suc ...
. Common techniques for doing so are to have different sections of a program use different
name space In computing Computing is any goal-oriented activity requiring, benefiting from, or creating computing machinery. It includes the study and experimentation of algorithmic processes and development of both computer hardware , hardware and softw ...
s, 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.


Typing

In
statically typed In programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various kinds of Input/output, output. Programming languages are used in computer programming to i ...
languages such as Go or ML, a variable also has a ''type'', meaning that only certain kinds of values can be stored in it. For example, a variable of type "
integer An integer (from the Latin Latin (, or , ) is a classical language belonging to the Italic branch of the Indo-European languages. Latin was originally spoken in the area around Rome, known as Latium. Through the power of the Roman Re ...
" is prohibited from storing text values. In
dynamically typed In programming languages, a type system is a logical system comprising a set of rules that assigns a property called a type (computer science), type to the various constructs of a computer program, such as variable (computer science), variables ...
languages such as
Python Python may refer to: * Pythonidae The Pythonidae, commonly known as pythons, are a family of nonvenomous snakes found in Africa, Asia, and Australia. Among its members are some of the largest snakes in the world. Ten genera and 42 species ...
, a variable's type is inferred by its value, and can change according to its value. In
Common Lisp Common Lisp (CL) is a dialect of the Lisp programming language Lisp (historically LISP) is a family of programming language A programming language is a formal language In mathematics Mathematics (from Ancient Greek, Greek: ) incl ...
, both situations exist simultaneously: A variable is given a type (if undeclared, it is assumed to be , 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++ C++ () is a general-purpose programming language In computer software, a general-purpose programming language is a programming language dedicated to a general-purpose, designed to be used for writing software in a wide variety of application ...

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
datatype In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of c ...
s 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 may determine the length of a list. Such a function may be parametric polymorphic by including a type variable in its
type signatureIn computer science, a type signature or type annotation defines the inputs and outputs for a function, subroutine or Method (computer programming), method. A type signature includes the number, types and order of the arguments contained by a functio ...
, since the number of elements in the list is independent of the elements' types.


Parameters

The ''formal parameters'' (or ''formal arguments'') of functions are also referred to as variables. For instance, in this
Python Python may refer to: * Pythonidae The Pythonidae, commonly known as pythons, are a family of nonvenomous snakes found in Africa, Asia, and Australia. Among its members are some of the largest snakes in the world. Ten genera and 42 species ...
code segment, >>> def addtwo(x): ... return x + 2 ... >>> addtwo(5) 7 the variable named is a ''
parameter A parameter (), generally, is any characteristic that can help in defining or classifying a particular system A system is a group of Interaction, interacting or interrelated elements that act according to a set of rules to form a unified wh ...
'' because it is given a value when the function is called. The integer 5 is the ''argument'' which gives its value. In most languages, function parameters have local scope. This specific variable named can only be referred to within the function (though of course other functions can also have variables called ).


Memory allocation

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 variable In computer science, a local variable is a Variable (programming), variable that is given ''local scope (programming), scope''. Local variable references in the subroutine, function or block (programming), block in which it is declared override the ...
s'', whose extent lasts for a single function call on the ''
call stack In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of Algor ...
'', and whose memory is automatically reclaimed when the function returns. More generally, in ''
name binding In programming language A programming language is a formal language comprising a Instruction set architecture, set of instructions that produce various kinds of Input/output, output. Programming languages are used in computer programming to impl ...
'', 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 Heap or HEAP may refer to: Computing and mathematics * Heap (data structure), a data structure commonly used to implement a priority queue * Heap (mathematics), a generalization of a group * Heap (programming) (or free store), an area of memory for ...
''. Bound variables have values. A value, however, is an abstraction, an idea; in implementation, a value is represented by some ''
data object In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of comp ...
'', which is stored somewhere in computer memory. The program, or the
runtime environment In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a particular task. Programming involves tasks such as analysis, gen ...
, 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—especially when the objects are no longer needed. In a garbage-collected language (such as C#,
Java Java ( id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 147.7 million people, Java is the world's List of ...
, Python, Golang and
Lisp Lisp (historically LISP) is a family of programming language A programming language is a formal language In logic, mathematics, computer science, and linguistics, a formal language consists of string (computer science), words whose symbo ...
), 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 the programmer) must explicitly allocate memory, and then later free it, to reclaim its memory. Failure to do so leads to
memory leak In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of , , ...
s, in which the heap is depleted as the program runs, risks eventual failure from exhausting available memory. When a variable refers to a
data structure In computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practical techniques for their application. Computer science is the study of ...

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.


Naming conventions

Unlike their mathematical counterparts, programming variables and constants commonly take multiple-character names, e.g. or . Single-character names are most commonly used only for auxiliary variables; for instance, , , for
array index ARRAY, also known as ARRAY Now, is an independent distribution company launched by film maker and former publicist Ava DuVernay Ava Marie DuVernay (; born August 24, 1972) is an American filmmaker. She won the directing award in the U.S. dram ...
variables. Some naming conventions are enforced at the language level as part of the language syntax which involves the format of valid identifiers. In almost all languages, variable names cannot start with a digit (0–9) and cannot contain whitespace characters. Whether or not punctuation marks are permitted in variable names varies from language to language; many languages only permit the
underscore Underscored or underlined text. An underscore, also called an underline, low line or low dash, is a line drawn under a segment of text. In proofreading Proofreading is the reading (activity), reading of a galley proof or an electronic copy of ...

underscore
("_") in variable names and forbid all other punctuation. In some programming languages,
sigil A sigil (; pl. ''sigilla'' or ''sigils'') is a type of symbol used in magic Magic or Magick may refer to: * Ceremonial magic, encompasses a wide variety of rituals of magic * Chaos magic#REDIRECT Chaos magic {{Redirect category shell, 1= { ...
s (symbols or punctuation) are affixed to variable identifiers to indicate the variable's datatype or scope. Case-sensitivity of variable names also varies between languages and some languages require the use of a certain case in naming certain entities;For example, Haskell requires that names of types start with a capital letter. Most modern languages are case-sensitive; some older languages are not. Some languages reserve certain forms of variable names for their own internal use; in many languages, names beginning with two underscores ("__") often fall under this category. However, beyond the basic restrictions imposed by a language, the naming of variables is largely a matter of style. At the
machine code In computer programming Computer programming is the process of designing and building an executable In computing, executable code, an executable file, or an executable program, sometimes simply referred to as an executable or binary, c ...
level, variable names are not used, so the exact names chosen do not matter to the computer. Thus names of variables identify them, for the rest they are just a tool for programmers to make programs easier to write and understand. Using poorly chosen variable names can make code more difficult to review than non-descriptive names, so names that are clear are often encouraged.How Not To Pick Variables
Retrieved July 11, 2012 EAD LINK/ref> Programmers often create and adhere to code style guidelines that offer guidance on naming variables or impose a precise naming scheme. Shorter names are faster to type but are less descriptive; longer names often make programs easier to read and the purpose of variables easier to understand. However, extreme verbosity in variable names can also lead to less comprehensible code.


Variable types (based on lifetime)

In terms of the classifications of variables, we can classify variables based on the lifetime of them. The different types of variables are static, stack-dynamic, explicit heap-dynamic, and implicit heap-dynamic. A
static variable In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming involves tasks such as: analysis, generat ...
is also known as global variable, it is bound to a memory cell before execution begins and remains to the same memory cell until termination. A typical example is the static variables in C and C++. A Stack-dynamic variable is known as local variable, which is bound when the declaration statement is executed, and it is deallocated when the procedure returns. The main examples are local variables in C subprograms and Java methods. Explicit Heap-Dynamic variables are nameless (abstract) memory cells that are allocated and deallocated by explicit run-time instructions specified by the programmer. The main examples are dynamic objects in C++ (via new and delete) and all objects in Java. Implicit Heap-Dynamic variables are bound to heap storage only when they are assigned values. Allocation and release occur when values are reassigned to variables. As a result, Implicit heap-dynamic variables have the highest degree of flexibility. The main examples are some variables in JavaScript, PHP and all variables in APL.


See also

* Control variable (programming) *
Non-local variableIn programming language theory Programming language theory (PLT) is a branch of computer science Computer science deals with the theoretical foundations of information, algorithms and the architectures of its computation as well as practica ...
*
Temporary variable In computer programming, a temporary variable is a variable (programming), variable with short object lifetime, lifetime, usually to hold data (computing), data that will soon be discarded, or before it can be placed at a more permanent memory loca ...
*
Variable interpolation In computer programming Computer programming is the process of designing and building an executable computer program to accomplish a specific computing result or to perform a specific task. Programming involves tasks such as: analysis, generati ...
*
Scalar (mathematics) A scalar is an element of a field Field may refer to: Expanses of open ground * Field (agriculture), an area of land used for agricultural purposes * Airfield, an aerodrome that lacks the infrastructure of an airport * Battlefield * Lawn, an ar ...


Notes


References

{{DEFAULTSORT:Variable (Programming) Programming language concepts Data types Type theory