HOME

TheInfoList



OR:

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 anal ...
, an assignment statement sets and/or re-sets the
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 ...
stored in the storage location(s) denoted by a variable
name A name is a term used for identification by an external observer. They can identify a class or category of things, or a single thing, either uniquely, or within a given context. The entity identified by a name is called its referent. A persona ...
; in other words, it copies a value into the variable. In most 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, the assignment statement (or expression) is a fundamental construct. Today, the most commonly used notation for this operation is ''x'' = ''expr'' (originally Superplan 1949–51, popularized by Fortran 1957 and C). The second most commonly used notation is ''x'' := ''expr'' (originally
ALGOL ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
1958, popularised by
Pascal Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Frenc ...
). Many other notations are also in use. In some languages, the symbol used is regarded as an operator (meaning that the assignment statement as a whole returns a value). Other languages define assignment as a statement (meaning that it cannot be used in an expression). Assignments typically allow a variable to hold different values at different times during its life-span and
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 * Cinema ...
. However, some languages (primarily strictly functional languages) do not allow that kind of "destructive" reassignment, as it might imply changes of non-local state. The purpose is to enforce referential transparency, i.e. functions that do not depend on the state of some variable(s), but produce the same results for a given set of parametric inputs at any point in time. Modern programs in other languages also often use similar strategies, although less strict, and only in certain parts, in order to reduce complexity, normally in conjunction with complementing methodologies such as data structuring,
structured programming Structured programming is a programming paradigm aimed at improving the clarity, quality, and development time of a computer program by making extensive use of the structured control flow constructs of selection ( if/then/else) and repetition ( ...
and object orientation.


Semantics

An assignment operation is a process in
imperative programming In computer science, imperative programming is a programming paradigm of software that uses statements that change a program's state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program ...
in which different values are associated with a particular variable name as time passes. The program, in such model, operates by changing its state using successive assignment statements. Primitives of imperative programming languages rely on assignment to do
iteration Iteration is the repetition of a process in order to generate a (possibly unbounded) sequence of outcomes. Each repetition of the process is a single iteration, and the outcome of each iteration is then the starting point of the next iteration. ...
. At the lowest level, assignment is implemented using machine operations such as MOVE or STORE.Crossing borders: Explore functional programming with Haskell
, by Bruce Tate
Variables are containers for values. It is possible to put a value into a variable and later replace it with a new one. An assignment operation modifies the current state of the executing program. Consequently, assignment is dependent on the concept of variables. In an assignment: * The ''expression'' is evaluated in the current state of the program. * The ''variable'' is assigned the computed value, replacing the prior value of that variable. Example: Assuming that a is a numeric variable, the assignment a := 2*a means that the content of the variable a is doubled after the execution of the statement. An example segment of C code: int x = 10; float y; x = 23; y = 32.4f; In this sample, the variable x is first declared as an int, and is then assigned the value of 10. Notice that the declaration and assignment occur in the same statement. In the second line, y is declared without an assignment. In the third line, x is reassigned the value of 23. Finally, y is assigned the value of 32.4. For an assignment operation, it is necessary that the value of the ''expression'' is well-defined (it is a valid rvalue) and that the ''variable'' represents a modifiable entity (it is a valid modifiable (non- const) lvalue). In some languages, typically
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 dyn ...
ones, it is not necessary to declare a variable prior to assigning it a value. In such languages, a variable is automatically declared the first time it is assigned to, with the scope it is declared in varying by language.


Single assignment

Any assignment that changes an existing value (e.g. x := x + 1) is disallowed in purely functional languages. In
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions tha ...
, assignment is discouraged in favor of single assignment, also called ''initialization''. Single assignment is an example of
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 ...
and differs from assignment as described in this article in that it can only be done once, usually when the variable is created; no subsequent reassignment is allowed. An evaluation of expression does not have a
side effect In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
if it does not change an observable state of the machine, and produces same values for same input. Imperative assignment can introduce side effects while destroying and making the old value unavailable while substituting it with a new one, and is referred to as ''destructive assignment'' for that reason in
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 lispin ...
and
functional programming In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions tha ...
, similar to destructive updating. Single assignment is the only form of assignment available in purely functional languages, such as
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 lan ...
, which do not have variables in the sense of imperative programming languages but rather named constant values possibly of compound nature with their elements progressively defined ''on-demand''. Purely functional languages can provide an opportunity for computation to be performed in parallel, avoiding the
von Neumann bottleneck The von Neumann architecture — also known as the von Neumann model or Princeton architecture — is a computer architecture based on a 1945 description by John von Neumann, and by others, in the '' First Draft of a Report on the EDVAC''. T ...
of sequential one step at a time execution, since values are independent of each other. Impure functional languages provide both single assignment as well as true assignment (though true assignment is typically used with less frequency than in imperative programming languages). For example, in Scheme, both single assignment (with let) and true assignment (with set!) can be used on all variables, and specialized primitives are provided for destructive update inside lists, vectors, strings, etc. In OCaml, only single assignment is allowed for variables, via the let ''name'' = ''value'' syntax; however destructive update can be used on elements of arrays and strings with separate <- operator, as well as on fields of records and objects that have been explicitly declared
mutable In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3. ...
(meaning capable of being changed after their initial declaration) by the programmer. Functional programming languages that use single assignment include
Clojure Clojure (, like ''closure'') is a dynamic and functional dialect of the Lisp programming language on the Java platform. Like other Lisp dialects, Clojure treats code as data and has a Lisp macro system. The current development process is comm ...
(for data structures, not vars), Erlang (it accepts multiple assignment if the values are equal, in contrast to Haskell), F#,
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 lan ...
,
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
(for constants),
Lava Lava is molten or partially molten rock (magma) that has been expelled from the interior of a terrestrial planet (such as Earth) or a moon onto its surface. Lava may be erupted at a volcano or through a fracture in the crust, on land or ...
,
OCaml OCaml ( , formerly Objective Caml) is a general-purpose, multi-paradigm programming language Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms. ...
, Oz (for dataflow variables, not cells), Racket (for some data structures like lists, not symbols), SASL, Scala (for vals),
SISAL Sisal (, ) (''Agave sisalana'') is a species of flowering plant native to southern Mexico, but widely cultivated and naturalized in many other countries. It yields a stiff fibre used in making rope and various other products. The term sisal may ...
,
Standard ML Standard ML (SML) is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of ...
. Non-
backtracking Backtracking is a class of algorithms for finding solutions to some computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate ("backtracks") as soon as it d ...
Prolog Prolog is a logic programming language associated with artificial intelligence and computational linguistics. Prolog has its roots in first-order logic, a formal logic, and unlike many other programming languages, Prolog is intended primarily ...
code can be considered ''explicit'' single-assignment, explicit in a sense that its (named) variables can be in explicitly unassigned state, or be set exactly once. In Haskell, by contrast, there can be no unassigned variables, and every variable can be thought of as being implicitly set to its value (or rather to a computational object that will produce its value ''on demand'') when it is created.


Value of an assignment

In some programming languages, an assignment statement returns a value, while in others it does not. In most
expression-oriented programming languages An expression-oriented programming language is a programming language in which every (or nearly every) construction is an expression and thus yields a value. The typical exceptions are macro definitions, preprocessor commands, and declarations ...
(for example, C), the assignment statement returns the assigned value, allowing such idioms as x = y = a, in which the assignment statement y = a returns the value of a, which is then assigned to x. In a statement such as , the return value of a function is used to control a loop while assigning that same value to a variable. In other programming languages,
Scheme A scheme is a systematic plan for the implementation of a certain idea. Scheme or schemer may refer to: Arts and entertainment * ''The Scheme'' (TV series), a BBC Scotland documentary series * The Scheme (band), an English pop band * ''The Schem ...
for example, the return value of an assignment is undefined and such idioms are invalid. In
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 lan ...
, there is no variable assignment; but operations similar to assignment (like assigning to a field of an array or a field of a mutable data structure) usually evaluate to the
unit type In the area of mathematical logic and computer science known as type theory, a unit type is a type that allows only one value (and thus can hold no information). The carrier (underlying set) associated with a unit type can be any singleton set. ...
, which is represented as (). This type has only one possible value, therefore containing no information. It is typically the type of an expression that is evaluated purely for its side effects.


Variant forms of assignment

Certain use patterns are very common, and thus often have special syntax to support them. These are primarily
syntactic sugar In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
to reduce redundancy in the source code, but also assists readers of the code in understanding the programmer's intent, and provides the compiler with a clue to possible optimization.


Augmented assignment

The case where the assigned value depends on a previous one is so common that many imperative languages, most notably C and the majority of its descendants, provide special operators called
augmented assignment Augmented assignment (or compound assignment) is the name given to certain assignment operators in certain programming languages (especially those derived from C). An augmented assignment is generally used to replace a statement where an operat ...
, like *=, so a = 2*a can instead be written as a *= 2. Beyond syntactic sugar, this assists the task of the compiler by making clear that in-place modification of the variable a is possible.


Chained assignment

A statement like w = x = y = z is called a chained assignment in which the value of z is assigned to multiple variables w, x, and y. Chained assignments are often used to initialize multiple variables, as in a = b = c = d = f = 0 Not all programming languages support chained assignment. Chained assignments are equivalent to a sequence of assignments, but the evaluation strategy differs between languages. For simple chained assignments, like initializing multiple variables, the evaluation strategy does not matter, but if the targets (l-values) in the assignment are connected in some way, the evaluation strategy affects the result. In some programming languages ( C for example), chained assignments are supported because assignments are expressions, and have values. In this case chain assignment can be implemented by having a right-associative assignment, and assignments happen right-to-left. For example, i = arr = f() is equivalent to arr = f(); i = arr /code>. 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 ...
they are also available for values of class types by declaring the appropriate return type for the assignment operator. In Python, assignment statements are not expressions and thus do not have a value. Instead, chained assignments are a series of statements with multiple targets for a single expression. The assignments are executed left-to-right so that i = arr = f() evaluates the expression f(), then assigns the result to the leftmost target, i, and then assigns the same result to the next target, arr /code>, using the new value of i. This is essentially equivalent to tmp = f(); i = tmp; arr = tmp though no actual variable is produced for the temporary value.


Parallel assignment

Some programming languages, such as APL,
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 fr ...
, Go,
JavaScript JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, of ...
(since 1.7), PHP,
Maple ''Acer'' () is a genus of trees and shrubs commonly known as maples. The genus is placed in the family Sapindaceae.Stevens, P. F. (2001 onwards). Angiosperm Phylogeny Website. Version 9, June 2008 nd more or less continuously updated since h ...
, Lua, occam 2,
Perl Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was offic ...
, Python, REBOL,
Ruby A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called ...
, and
PowerShell PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-sou ...
allow several variables to be assigned in parallel, with syntax like: a, b := 0, 1 which simultaneously assigns 0 to a and 1 to b. This is most often known as parallel assignment; it was introduced in CPL in 1963, under the name simultaneous assignment, and is sometimes called multiple assignment, though this is confusing when used with "single assignment", as these are not opposites. If the right-hand side of the assignment is a single variable (e.g. an array or structure), the feature is called unpacking or destructuring assignment: var list := a, b := list The list will be unpacked so that 0 is assigned to a and 1 to b. Furthermore, a, b := b, a swaps the values of a and b. In languages without parallel assignment, this would have to be written to use a temporary variable var t := a a := b b := t since a := b; b := a leaves both a and b with the original value of b. Some languages, such as Go and Python, combine parallel assignment, tuples, and automatic tuple unpacking to allow multiple return values from a single function, as in this Python example, def f(): return 1, 2 a, b = f() while other languages, such as C# and
Rust Rust is an iron oxide, a usually reddish-brown oxide formed by the reaction of iron and oxygen in the catalytic presence of water or air moisture. Rust consists of hydrous iron(III) oxides (Fe2O3·nH2O) and iron(III) oxide-hydroxide (FeO( ...
, shown here, require explicit tuple construction and deconstruction with parentheses: // Valid C# or Rust syntax (a, b) = (b, a); // C# tuple return (string, int) f() => ("foo", 1); var (a, b) = f(); // Rust tuple return let f = , , ("foo", 1); let (a, b) = f(); This provides an alternative to the use of output parameters for returning multiple values from a function. This dates to CLU (1974), and CLU helped popularize parallel assignment generally. C# additionally allows generalized ''deconstruction assignment'' with implementation defined by the expression on the right-hand side, as the compiler searches for an appropriate instance or
extension Extension, extend or extended may refer to: Mathematics Logic or set theory * Axiom of extensionality * Extensible cardinal * Extension (model theory) * Extension (predicate logic), the set of tuples of values that satisfy the predicate * Ext ...
Deconstruct method on the expression, which must have output parameters for the variables being assigned to. For example, one such method that would give the
class Class or The Class may refer to: Common uses not otherwise categorized * Class (biology), a taxonomic rank * Class (knowledge representation), a collection of individuals or objects * Class (philosophy), an analytical concept used differently ...
it appears in the same behavior as the return value of f() above would be void Deconstruct(out string a, out int b) In C and C++, the comma operator is similar to parallel assignment in allowing multiple assignments to occur within a single statement, writing a = 1, b = 2 instead of a, b = 1, 2. This is primarily used in for loops, and is replaced by parallel assignment in other languages such as Go. However, the above C++ code does not ensure perfect simultaneity, since the right side of the following code a = b, b = a+1 is evaluated after the left side. In languages such as Python, a, b = b, a+1 will assign the two variables concurrently, using the initial value of a to compute the new b.


Assignment versus equality

The use of the equals sign = as an assignment operator has been frequently criticized, due to the conflict with equals as comparison for equality. This results both in confusion by novices in writing code, and confusion even by experienced programmers in reading code. The use of equals for assignment dates back to Heinz Rutishauser's language Superplan, designed from 1949 to 1951, and was particularly popularized by Fortran: Beginning programmers sometimes confuse assignment with the
relational operator In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality (''e.g.'', ) and inequalities (''e.g.'', ). In pr ...
for equality, as "=" means equality in mathematics, and is used for assignment in many languages. But assignment alters the value of a variable, while equality testing tests whether two expressions have the same value. In some languages, such as
BASIC BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
, a single equals sign ("=") is used for both the assignment operator and the equality relational operator, with context determining which is meant. Other languages use different symbols for the two operators. For example: * In
ALGOL ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by the ...
and
Pascal Pascal, Pascal's or PASCAL may refer to: People and fictional characters * Pascal (given name), including a list of people with the name * Pascal (surname), including a list of people and fictional characters with the name ** Blaise Pascal, Frenc ...
, the assignment operator is a colon and an equals sign (":=") while the equality operator is a single equals ("="). * In C, the assignment operator is a single equals sign ("=") while the equality operator is a pair of equals signs ("

"
). * In R, the assignment operator is basically <-, as in x <- value, but a single equals sign can be used in certain contexts. The similarity in the two symbols can lead to errors if the programmer forgets which form ("=", "

", ":=") is appropriate, or mistypes "=" when "

" was intended. This is a common programming problem with languages such as C (including one famous attempt to backdoor the Linux kernel), where the assignment operator also returns the value assigned (in the same way that a function returns a value), and can be validly nested inside expressions. If the intention was to compare two values in an if statement, for instance, an assignment is quite likely to return a value interpretable as Boolean true, in which case the then clause will be executed, leading the program to behave unexpectedly. Some language processors (such as gcc) can detect such situations, and warn the programmer of the potential error.


Notation

The two most common representations for the copying assignment are
equals sign The equals sign (British English, Unicode) or equal sign (American English), also known as the equality sign, is the mathematical symbol , which is used to indicate equality in some well-defined sense. In an equation, it is placed between tw ...
(=) and colon-equals (:=). Both forms may semantically denote either an assignment ''statement'' or an assignment '' operator'' (which also has a value), depending on language and/or usage. : Other possibilities include a left arrow or a keyword, though there are other, rarer, variants: : Mathematical pseudo code assignments are generally depicted with a left-arrow. Some platforms put the expression on the left and the variable on the right: : Some expression-oriented languages, such as
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 lispin ...
and Tcl, uniformly use prefix (or postfix) syntax for all statements, including assignment. :


See also

*
Assignment operator in C++ In the C++ programming language, the assignment operator, =, is the operator used for assignment. Like most other operators in C++, it can be overloaded. The copy assignment operator, often just called the "assignment operator", is a special case ...
*
Operator (programming) In computer programming, operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically. Common simple examples include arithmetic (e.g. addition with ), c ...
*
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 ...
*
Unification (computing) In logic and computer science, unification is an algorithmic process of solving equations between symbolic expressions. Depending on which expressions (also called ''terms'') are allowed to occur in an equation set (also called ''unification prob ...
*
Immutable object In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created.Goetz et al. ''Java Concurrency in Practice''. Addison Wesley Professional, 2006, Section 3. ...
*
Const-correctness In some programming languages, const is a type qualifier (a keyword applied to a data type) that indicates that the data is read-only. While this can be used to declare constants, in the C family of languages differs from similar constructs i ...


Notes


References

{{reflist, 2 Programming language concepts Assignment operations Articles with example C code