Incomputer programming,anassignment statementsets and/or re-sets thevaluestored in the storage location(s) denoted by avariablename;in other words, it copies a value into the variable. In mostimperativeprogramming languages,the assignment statement (or expression) is a fundamental construct.
Today, the most commonly used notation for this operation isx=expr
(originallySuperplan1949–51, popularized byFortran1957 andC). The second most commonly used notation is[1]x:=expr
(originallyALGOL1958, popularised byPascal).[2]Many other notations are also in use. In some languages, the symbol used is regarded as anoperator(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 andscope.However, some languages (primarilystrictly functionallanguages) do not allow that kind of "destructive" reassignment, as it might imply changes of non-local state. The purpose is to enforcereferential 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 asdata structuring,structured programmingandobject orientation.
Semantics
editAn assignment operation is a process inimperative programmingin which different values are associated with a particular variable name as time passes.[1]The program, in such model, operates by changing its state using successive assignment statements.[2][3]Primitives of imperative programming languages rely on assignment to doiteration.[4]At the lowest level, assignment is implemented usingmachine operationssuch asMOVE
orSTORE
.[2][4]
Variablesare 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.[3]Consequently, assignment is dependent on the concept ofvariables.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 thata
is a numeric variable, the assignmenta:= 2*a
means that the content of the variablea
is doubled after the execution of the statement.
An example segment ofCcode:
intx=10;
floaty;
x=23;
y=32.4f;
In this sample, the variablex
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 theexpression
is well-defined (it is a validrvalue) and that thevariable
represents a modifiable entity (it is a valid modifiable (non-const)lvalue). In some languages, typicallydynamicones, 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
editAny assignment that changes an existing value (e.g.x:= x + 1
) is disallowed inpurely functionallanguages.[4]Infunctional programming,assignment is discouraged in favor of single assignment, more commonly known asinitialization.Single assignment is an example ofname bindingand 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 an expression does not have aside effectif it does not change an observable state of the machine,[5]other than producing the result, and always produces same value for the same input.[4]Imperative assignment can introduce side effects while destroying and making the old value unavailable while substituting it with a new one,[6]and is referred to asdestructive assignmentfor that reason inLISPandfunctional programming,similar todestructive updating.
Single assignment is the only form of assignment available in purely functional languages, such asHaskell,which do not have variables in the sense of imperative programming languages[4]but rather named constant values possibly of compound nature, with their elements progressively definedon-demand,for thelazylanguages. Purely functional languages can provide an opportunity forcomputation to be performed in parallel,avoiding thevon Neumann bottleneckof sequential one step at a time execution, since values are independent of each other.[7]
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 (withlet
) and true assignment (withset!
) 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 theletname=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 declaredmutable(meaning capable of being changed after their initial declaration) by the programmer.
Functional programming languages that use single assignment includeClojure(for data structures, not vars),Erlang(it accepts multiple assignment if the values are equal, in contrast to Haskell),F#,Haskell,JavaScript(for constants), Lava,OCaml,Oz(for dataflow variables, not cells),Racket(for some data structures like lists, not symbols),SASL,Scala(for vals),SISAL,Standard ML.Non-backtrackingPrologcode can be consideredexplicitsingle-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, when it is created, to its value (or rather to a computational object that will produce its valueon demand).
Value of an assignment
editIn some programming languages, an assignment statement returns a value, while in others it does not.
In mostexpression-oriented programming languages(for example,C), the assignment statement returns the assigned value, allowing such idioms asx = y = a
,in which the assignment statementy = a
returns the value ofa
,which is then assigned tox
.In a statement such aswhile((ch=getchar())!=EOF){…}
,the return value of a function is used to control a loop while assigning that same value to a variable.
In other programming languages,Schemefor example, the return value of an assignment is undefined and such idioms are invalid.
InHaskell,[8]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 theunit type,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
editCertain use patterns are very common, and thus often have special syntax to support them. These are primarilysyntactic sugarto 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
editThe case where the assigned value depends on a previous one is so common that many imperative languages, most notablyCand the majority of its descendants, provide special operators calledaugmented assignment,like*=
,soa = 2*a
can instead be written asa *= 2
.[3]Beyond syntactic sugar, this assists the task of the compiler by making clear that in-place modification of the variablea
is possible.
Chained assignment
editA statement likew = x = y = z
is called achained assignmentin which the value ofz
is assigned to multiple variablesw, x,
andy
.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 (Cfor example), chained assignments are supported because assignments are expressions, and have values. In this case chain assignment can be implemented by having aright-associative assignment,and assignments happen right-to-left. For example,i = arr[i] = f()
is equivalent toarr[i] = f(); i = arr[i]
.InC++they are also available for values of class types by declaring the appropriate return type for the assignment operator.
InPython,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 thati = arr[i] = f()
evaluates the expressionf()
,then assigns the result to the leftmost target,i
,and then assigns the same result to the next target,arr[i]
,using the new value ofi
.[9]This is essentially equivalent totmp = f(); i = tmp; arr[i] = tmp
though no actual variable is produced for the temporary value.
Parallel assignment
editSome programming languages, such asAPL,Common Lisp,[10]Go,[11]JavaScript(since 1.7),PHP,Maple,Lua,occam 2,[12]Perl,[13]Python,[14]REBOL,Ruby,[15]andPowerShellallow several variables to be assigned in parallel, with syntax like:
a, b:= 0, 1
which simultaneously assigns 0 toa
and 1 tob
.This is most often known asparallel assignment;it was introduced inCPLin 1963, under the namesimultaneous assignment,[16]and is sometimes calledmultiple 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 calledunpacking[17]ordestructuring assignment:[18]
varlist:= {0, 1} a, b:= list
The list will be unpacked so that 0 is assigned toa
and 1 tob
.Furthermore,
a, b:= b, a
swaps the values ofa
andb
.In languages without parallel assignment, this would have to be written to use a temporary variable
vart:= a a:= b b:= t
sincea:= b; b:= a
leaves botha
andb
with the original value ofb
.
Some languages, such asGo,F#andPython,combine parallel assignment, tuples, and automatictuple unpackingto allow multiple return values from a single function, as in this Python example,
deff():
return1,2
a,b=f()
while other languages, such asC#andRust,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
letf=||("foo",1);
let(a,b)=f();
This provides an alternative to the use ofoutput parametersfor returning multiple values from a function. This dates toCLU(1974), and CLU helped popularize parallel assignment generally.
C# additionally allows generalizeddeconstruction assignmentwith implementation defined by the expression on the right-hand side, as the compiler searches for an appropriateinstanceorextensionDeconstruct
method on the expression, which must have output parameters for the variables being assigned to.[19]For example, one such method that would give theclassit appears in the same behavior as the return value off()
above would be
voidDeconstruct(outstringa,outintb){a="foo";b=1;}
In C and C++, thecomma operatoris similar to parallel assignment in allowing multiple assignments to occur within a single statement, writinga = 1, b = 2
instead ofa, b = 1, 2
.
This is primarily used infor loops,and is replaced by parallel assignment in other languages such as Go.[20]
However, the above C++ code does not ensure perfect simultaneity, since the right side of the following codea = 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
editThe 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 toHeinz Rutishauser's languageSuperplan,designed from 1949 to 1951, and was particularly popularized by Fortran:
A notorious example for a bad idea was the choice of the equal sign to denote assignment. It goes back to Fortran in 1957[a]and has blindly been copied by armies of language designers. Why is it a bad idea? Because it overthrows a century old tradition to let “=” denote a comparison for equality, a predicate which is either true or false. But Fortran made it to mean assignment, the enforcing of equality. In this case, the operands are on unequal footing: The left operand (a variable) is to be made equal to the right operand (an expression). x = y does not mean the same thing as y = x.[21]
— Niklaus Wirth,Good Ideas, Through the Looking Glass
Beginning programmers sometimes confuse assignment with therelational operatorfor equality, as "=" meansequalityin 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 asBASIC,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.[22]For example:
- InALGOLandPascal,the assignment operator is a colon and an equals sign (
":="
) while the equality operator is a single equals ("="
). - InC,the assignment operator is a single equals sign (
"="
) while the equality operator is a pair of equals signs ("=="
). - InR,the assignment operator is basically
<-
,as inx <- 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),[23]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 anif
statement, for instance, an assignment is quite likely to return a value interpretable as Boolean true, in which case thethen
clause will be executed, leading the program to behave unexpectedly. Some language processors (such asgcc) can detect such situations, and warn the programmer of the potential error.[24][25]
Notation
editThe two most common representations for the copying assignment areequals sign(=
) and colon-equals (:=
). Both forms may semantically denote either an assignmentstatementor an assignmentoperator(which also has a value), depending on language and/or usage.
variable=expression
Fortran,PL/I,C(anddescendantssuch asC++,Java,etc.),Bourne shell,Python,Go(assignment to pre-declared variables),R,PowerShell,Nim,etc. variable:=expression
ALGOL(and derivatives),Simula,CPL,BCPL,Pascal[26](and descendants such asModula),Mary,PL/M,Ada,Smalltalk,Eiffel,[27][28]Oberon,Dylan,[29]Seed7,Python(an assignment expression),[30]Go(shorthand for declaring and defining a variable),[31]Io,AMPL,ML(assigning to a reference value),[32]AutoHotkeyetc.
Other possibilities include a left arrow or a keyword, though there are other, rarer, variants:
variable<<expression
Magik variable<-expression
F#,OCaml,R,S variable<<-expression
R assign( "variable",expression)
R variable←expression
APL,[33]Smalltalk,Atari 2600 BASIC Programming variable=:expression
J LETvariable=expression
BASIC letvariable:=expression
XQuery setvariabletoexpression
AppleScript setvariable=expression
C shell Set-Variablevariable(expression)
PowerShell variable:expression
Macsyma, Maxima,K variable:expression
Rebol varvariableexpression
mIRC scripting language reference-variable:-reference-expression
Simula
Mathematicalpseudo codeassignments are generally depicted with a left-arrow.
Some platforms put the expression on the left and the variable on the right:
MOVEexpressionTOvariable
COBOL expression→variable
TI-BASIC,Casio BASIC expression->variable
POP-2,BETA,R putexpressionintovariable
HyperTalk,LiveCode PUTexpressionINvariable
ABC
Some expression-oriented languages, such asLisp[34][35]and Tcl, uniformly use prefix (or postfix) syntax for all statements, including assignment.
See also
editNotes
edit- ^Use of
=
predates Fortran, though it was popularized by Fortran.
References
edit- ^ab"2cs24 Declarative".www.csc.liv.ac.uk.Archived fromthe originalon 24 April 2006.Retrieved20 April2018.
- ^abc"Imperative Programming".uah.edu.Archived fromthe originalon 4 March 2016.Retrieved20 April2018.
- ^abcRuediger-Marcus Flaig (2008).Bioinformatics programming in Python: a practical course for beginners.Wiley-VCH. pp. 98–99.ISBN978-3-527-32094-3.Retrieved25 December2010.
- ^abcdeCrossing borders: Explore functional programming with HaskellArchivedNovember 19, 2010, at theWayback Machine,by Bruce Tate
- ^Mitchell, John C.(2003).Concepts in programming languages.Cambridge University Press. p. 23.ISBN978-0-521-78098-8.Retrieved3 January2011.
- ^"Imperative Programming Languages (IPL)"(PDF).gwu.edu.Archived fromthe original(PDF)on 2011-07-16.Retrieved20 April2018.
- ^John C. Mitchell (2003).Concepts in programming languages.Cambridge University Press. pp. 81–82.ISBN978-0-521-78098-8.Retrieved3 January2011.
- ^Hudak, Paul (2000).The Haskell School of Expression: Learning Functional Programming Through Multimedia.Cambridge: Cambridge University Press.ISBN0-521-64408-9.
- ^"7. Simple statements — Python 3.6.5 documentation".docs.python.org.Retrieved20 April2018.
- ^"CLHS: Macro SETF, PSETF".Common Lisp Hyperspec.LispWorks.Retrieved23 April2019.
- ^The Go Programming Language Specification:Assignments
- ^INMOS Limited, ed. (1988).Occam 2 Reference Manual.New Jersey: Prentice Hall.ISBN0-13-629312-3.
- ^Wall, Larry;Christiansen, Tom; Schwartz, Randal C. (1996).Perl Programming Language(2 ed.). Cambridge: O´Reilly.ISBN1-56592-149-6.
- ^Lutz, Mark (2001).Python Programming Language(2 ed.). Sebastopol: O´Reilly.ISBN0-596-00085-5.
- ^Thomas, David; Hunt, Andrew (2001).Programming Ruby: The Pragmatic Programmer's Guide.Upper Saddle River: Addison Wesley.ISBN0-201-71089-7.
- ^D.W. Barronet al.,"The main features of CPL",Computer Journal6:2:140 (1963).full text (subscription)
- ^"PEP 3132 -- Extended Iterable Unpacking".legacy.python.org.Retrieved20 April2018.
- ^"Destructuring assignment".MDN Web Docs.Retrieved20 April2018.
- ^"Deconstructing tuples and other types".Microsoft Docs.Microsoft.Retrieved29 August2019.
- ^Effective Go:for, "Finally, Go has no comma operator and ++ and -- are statements not expressions. Thus if you want to run multiple variables in a for you should use parallel assignment (although that precludes ++ and --)."
- ^Niklaus Wirth."Good Ideas, Through the Looking Glass".CiteSeerX10.1.1.88.8309.
- ^"C++ Programming Language. Basics".ntu.edu.sg.2013-06-01.Retrieved2024-06-21.
- ^Corbet (6 November 2003)."An attempt to backdoor the kernel".lwn.net.Retrieved2024-06-21.
- ^"Static Analyzer Options (Using the GNU Compiler Collection (GCC))".gcc.gnu.org.Retrieved2024-06-21.
- ^Deitel, Paul; Deitel, Harvey (2022-10-25)."C++ Control Statements, Part 2".Domyassignments.Retrieved2024-06-21.
- ^Moore, Lawrie (1980).Foundations of Programming with Pascal.New York: John Wiley & Sons.ISBN0-470-26939-1.
- ^Meyer, Bertrand(1992).Eiffel the Language.Hemel Hempstead: Prentice Hall International(UK).ISBN0-13-247925-7.
- ^Wiener, Richard (1996).An Object-Oriented Introduction to Computer Science Using Eiffel.Upper Saddle River, New Jersey: Prentice Hall.ISBN0-13-183872-5.
- ^Feinberg, Neal; Keene, Sonya E.; Mathews, Robert O.; Withington, P. Tucker (1997).Dylan Programming.Massachusetts: Addison Wesley.ISBN0-201-47976-1.
- ^"PEP 572 – Assignment Expressions".python.org.28 February 2018.Retrieved4 March2020.
- ^"The Go Programming Language Specification - The Go Programming Language".golang.org.Retrieved20 April2018.
- ^Ullman, Jeffrey D. (1998).Elements of ML Programming: ML97 Edition.Englewood Cliffs, New Jersey: Prentice Hall.ISBN0-13-790387-1.
- ^Iverson, Kenneth E.(1962).A Programming Language.John Wiley and Sons.ISBN0-471-43014-5.Archived fromthe originalon 2009-06-04.Retrieved2010-05-09.
- ^Graham, Paul(1996).ANSI Common Lisp.New Jersey: Prentice Hall.ISBN0-13-370875-6.
- ^Steele, Guy L.(1990).Common Lisp: The Language.Lexington: Digital Press.ISBN1-55558-041-6.
- ^Dybvig, R. Kent (1996).The Scheme Programming Language: ANSI Scheme.New Jersey: Prentice Hall.ISBN0-13-454646-6.
- ^Smith, Jerry D. (1988).Introduction to Scheme.New Jersey: Prentice Hall.ISBN0-13-496712-7.
- ^Abelson, Harold; Sussman, Gerald Jay; Sussman, Julie (1996).Structure and Interpretation of Computer Programs.New Jersey: McGraw-Hill.ISBN0-07-000484-6.