In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, a variable is an abstract storage location paired with an associated
symbolic name, which contains some known or unknown quantity of information referred to as a ''
value
Value or values may refer to:
Ethics and social
* Value (ethics) wherein said concept may be construed as treating actions themselves as abstract objects, associating value to them
** Values (Western philosophy) expands the notion of value beyo ...
''; or in simpler terms, a variable is a named container for a particular set of bits or
type of data (like
integer
An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign (−1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the language ...
,
float
Float may refer to:
Arts and entertainment Music Albums
* ''Float'' (Aesop Rock album), 2000
* ''Float'' (Flogging Molly album), 2008
* ''Float'' (Styles P album), 2013
Songs
* "Float" (Tim and the Glory Boys song), 2022
* "Float", by Bush ...
,
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), a Canadian anim ...
etc...). A variable can eventually be associated with or identified by a
memory address
In computing, a memory address is a reference to a specific memory location used at various levels by software and hardware. Memory addresses are fixed-length sequences of digits conventionally displayed and manipulated as unsigned integers. Su ...
. 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, source code, or simply code, is any collection of code, with or without comments, written using a human-readable programming language, usually as plain text. The source code of a program is specially designed to facilitate the wo ...
can be
bound
Bound or bounds may refer to:
Mathematics
* Bound variable
* Upper and lower bounds, observed limits of mathematical functions
Physics
* Bound state, a particle that has a tendency to remain localized in one or more regions of space
Geography
*B ...
to a
value
Value or values may refer to:
Ethics and social
* Value (ethics) wherein said concept may be construed as treating actions themselves as abstract objects, associating value to them
** Values (Western philosophy) expands the notion of value beyo ...
during
run time
Run(s) or RUN may refer to:
Places
* Run (island), one of the Banda Islands in Indonesia
* Run (stream), a stream in the Dutch province of North Brabant
People
* Run (rapper), Joseph Simmons, now known as "Reverend Run", from the hip-hop group ...
, 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, an equation is a formula that expresses the equality of two expressions, by connecting them with the equals sign . The word ''equation'' and its cognates in other languages may have subtly different meanings; for example, in ...
or
formula
In science, a formula is a concise way of expressing information symbolically, as in a mathematical formula or a ''chemical formula''. The informal use of the term ''formula'' in science refers to the general construct of a relationship betwee ...
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 and related disciplines, aliasing is an effect that causes different signals to become indistinguishable (or ''aliases'' of one another) when sampled. It also often refers to the distortion or artifact that results when a ...
. 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, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
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 programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming ...
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 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 tool
* Pure-FTPd, F ...
functional
Functional may refer to:
* Movements in architecture:
** Functionalism (architecture)
** Form follows function
* Functional group, combination of atoms within molecules
* Medical conditions without currently visible organic basis:
** Functional sy ...
and
logic language
Logic programming is a programming paradigm which is largely based on formal logic. Any program written in a logic programming language is a set of sentences in logical form, expressing facts and rules about some problem domain. Major logic prog ...
s, variables are
bound
Bound or bounds may refer to:
Mathematics
* Bound variable
* Upper and lower bounds, observed limits of mathematical functions
Physics
* Bound state, a particle that has a tendency to remain localized in one or more regions of space
Geography
*B ...
to expressions and keep a single value during their entire
lifetime
Lifetime may refer to:
* Life expectancy, the length of time a person is expected to remain alive
Arts, entertainment, and media
Music
* Lifetime (band), a rock band from New Jersey
* ''Life Time'' (Rollins Band album), by Rollins Band
* ...
due to the requirements of
referential transparency
In computer science, referential transparency and referential opacity are properties of parts of computer programs. An expression is called ''referentially transparent'' if it can be replaced with its corresponding value (and vice-versa) withou ...
. In imperative languages, the same behavior is exhibited by (named)
constants (symbolic constants), which are typically contrasted with (normal) variables.
Depending on the
type system
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
of a programming language, variables may only be able to store a specified
data type
In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
(e.g.
integer
An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign (−1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the language ...
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), a Canadian anim ...
). 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, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The scope is the lexical context, particularly the function or b ...
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 proper ...
of the variable, such as access permission,
locks
Lock(s) may refer to:
Common meanings
*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, as in a canal
Arts and entertainment
* ''Lock ...
,
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
Scope or scopes may refer to:
People with the surname
* Jamie Scope (born 1986), English footballer
* John T. Scopes (1900–1970), central figure in the Scopes Trial regarding the teaching of evolution
Arts, media, and entertainment
* Cinem ...
'' 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. 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 implementa ...
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 scope
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts o ...
" is meaningful only within a certain function/
subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions may ...
, or more finely within a block of expressions/statements (accordingly with
function scope
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts o ...
or
block scope
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts o ...
); this is static resolution, performable at parse-time or compile-time. Alternatively, a variable with
dynamic scope
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
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''. A local variable reference in the subroutine, function or block (programming), block in which it is declared overrides ...
s". A "
global variable
In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the ''global environment'' or ''global s ...
", 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 δυναμικός ''dynamikos'' "powerful", from δύναμις ''dynamis'' "power") or dynamic may refer to:
Physics and engineering
* Dynamics (mechanics)
** Aerodynamics, the study of the motion of air
** Analytical dynam ...
) 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 treatment or landfill. Waste collection also includes the curbside collection of recyclable m ...
, a variable whose extent permanently outlasts its scope can result in a
memory leak
In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that Computer memory, memory which is no longer needed is not released. A memory leak may also happe ...
, 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, a local variable is a variable that is given ''local scope''. A local variable reference in the function or block in which it is declared overrides the same variable name in the larger scope. In programming languages with on ...
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
Wild, wild, wilds or wild may refer to:
Common meanings
* Wild animal
* Wilderness, a wild natural environment
* Wildness, the quality of being wild or untamed
Art, media and entertainment Film and television
* ''Wild'' (2014 film), a 2014 Am ...
), 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 are pointers that do not point to a valid object of the appropriate type. These are special cases of memory safety violations. More generally, dangling references and wild references are ...
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, action at a distance is the concept that an object can be affected without being physically touched (as in mechanical contact) by another object. That is, it is the non-local interaction of objects that are separated in space.
Non-c ...
. Common techniques for doing so are to have different sections of a program use different
name space
In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified.
Namespaces ...
s, or to make individual variables "private" through either
dynamic variable scoping
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts o ...
or
lexical variable scoping
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other parts ...
.
Many programming languages employ a reserved value (often named ''
null
Null may refer to:
Science, technology, and mathematics Computing
*Null (SQL) (or NULL), a special marker and keyword in SQL indicating that something has no value
*Null character, the zero-valued ASCII character, also designated by , often used ...
'' or ''nil'') to indicate an invalid or uninitialized variable.
Typing
In
statically typed
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
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 is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign (−1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the language ...
" is prohibited from storing text values.
In
dynamically typed
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer progra ...
languages such as
Python
Python may refer to:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
, 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, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fro ...
, both situations exist simultaneously: A variable is given a type (if undeclared, it is assumed to be , the universal
supertype
In programming language theory, subtyping (also subtype polymorphism or inclusion polymorphism) is a form of type polymorphism in which a subtype is a datatype that is related to another datatype (the supertype) by some notion of substitutability, ...
) 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 object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part o ...
'' in
C++
C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
) 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 and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
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 signature
In computer science, a type signature or type annotation defines the inputs and outputs for a function, subroutine or method. A type signature includes the number, types, and order of the arguments contained by a function. A type signature is typ ...
, 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:
Snakes
* Pythonidae, a family of nonvenomous snakes found in Africa, Asia, and Australia
** ''Python'' (genus), a genus of Pythonidae found in Africa and Asia
* Python (mythology), a mythical serpent
Computing
* Python (pro ...
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 (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
'' 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''. A local variable reference in the subroutine, function or block (programming), block in which it is declared overrides ...
s'', whose extent lasts for a single function call on the ''
call stack
In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or ma ...
'', and whose memory is automatically reclaimed when the function returns. More generally, in ''
name binding
In programming languages, name binding is the association of entities (data and/or code) with identifiers. An identifier bound to an object is said to reference that object. Machine languages have no built-in notion of identifiers, but name-objec ...
'', 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 f ...
''.
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, an object can be a variable, a data structure, a function, or a method. As regions of memory, they contain value and are referenced by identifiers.
In the object-oriented programming paradigm, ''object'' can be a combinatio ...
'', which is stored somewhere in computer memory. The program, or the
runtime environment
In computer programming, a runtime system or runtime environment is a sub-system that exists both in the computer where a program is created, as well as in the computers where the program is intended to be run. The name comes from the compile t ...
, 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 151.6 million people, Java is the world's List ...
, Python, Golang and
Lisp
A lisp is a speech impairment in which a person misarticulates sibilants (, , , , , , , ). These misarticulations often result in unclear speech.
Types
* A frontal lisp occurs when the tongue is placed anterior to the target. Interdental lisping ...
), 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, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that Computer memory, memory which is no longer needed is not released. A memory leak may also happe ...
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, a data structure is a data organization, management, and storage format that is usually chosen for efficient access to data. More precisely, a data structure is a collection of data values, the relationships among them, a ...
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
In computer science, an array is a data structure consisting of a collection of ''elements'' (values or variables), each identified by at least one ''array index'' or ''key''. An array is stored such that the position of each element can be c ...
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
An underscore, ; also called an underline, low line, or low dash; is a line drawn under a segment of text. In proofreading, underscoring is a convention that says "set this text in italic type", traditionally used on Manuscript (publishing), man ...
("_") in variable names and forbid all other punctuation. In some programming languages,
sigil
A sigil () is a type of symbol used in magic. The term has usually referred to a pictorial signature of a deity or spirit. In modern usage, especially in the context of chaos magic, sigil refers to a symbolic representation of the practitioner ...
s (symbols or punctuation) are affixed to variable identifiers to indicate the variable's datatype or scope.
Case-sensitivity In computers, case sensitivity defines whether letter case, uppercase and lowercase letters are treated as distinct (case-sensitive) or equivalent (case-insensitive). For instance, when users interested in learning about dogs search an e-book, "dog" ...
of variable names also varies between languages and some languages require the use of a certain case in naming certain entities;
[For example, ]Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lang ...
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, machine code is any low-level programming language, consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). Each instruction causes the CPU to perform a very ...
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](_blank)
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)
We can classify variables based on their lifetime. The different types of variables are static, stack-dynamic, explicit heap-dynamic, and implicit heap-dynamic. A static variable
In computer programming, a static variable is a variable that has been allocated "statically", meaning that its lifetime (or "extent") is the entire run of the program. This is in contrast to shorter-lived automatic variables, whose storage is ...
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)
In computer programming, a control variable is a program variable that is used to regulate the flow of control of the program.
In definite iteration, control variables are variables which are successively assigned (or bound to) values from a pre ...
* Non-local variable
In programming language theory, a non-local variable is a variable that is not defined in the local scope. While the term can refer to global variables, it is primarily used in the context of nested and anonymous functions where some variables can ...
* Temporary variable
In computer programming, a temporary variable is a variable with short lifetime, usually to hold 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 ...
* Variable interpolation
In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders ...
* Scalar (mathematics)
A scalar is an element of a field which is used to define a ''vector space''.
In linear algebra, real numbers or generally elements of a field are called scalars and relate to vectors in an associated vector space through the operation of scala ...
Notes
References
{{DEFAULTSORT:Variable (Programming)
Programming language concepts
Data types
Type theory