Jump to content

Augmented assignment

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Antaeus Feldspar (talk | contribs) at 05:26, 20 December 2004 (started stub). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

Augmented assignment is the name given to certain operators in certain programming languages (especially those derived from C). An augmented assignment is generally used to replace a statement where an operator takes a variable as one of its arguments and then assigns the result back to the same variable.

For example, the following statement or some variation of it can be found in many programs:

x = x + 1

This means "find the number stored in the variable x, add 1 to it, and store the result of the addition in the variable x." As simple as this seems, it has an inefficiency, in that the location of variable x has to be looked up twice. In comparsion, here is the augmented assignment version:

x += 1

This version looks up the location of variable x just once, and modifies it in place.

In general, most operators that can take a variable as one of their arguments and return a result of the same type have an augmented assignment equivalent that assigns the result back to the variable in place, including arithmetic operators, bitshift operators, and bitwise operators.