Increment And Decrement Operators
   HOME

TheInfoList



OR:

Increment and decrement operators are unary operators that ''add'' or ''subtract'' one, to or from their
operand In mathematics, an operand is the object of a mathematical operation, i.e., it is the object or quantity that is operated on. Example The following arithmetic expression shows an example of operators and operands: :3 + 6 = 9 In the above examp ...
, respectively. They are commonly implemented 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. C-like languages feature two versions (pre- and post-) of each operator with slightly different semantics. In languages syntactically derived from B (including C and its various derivatives), the increment operator is written as ++ and the decrement operator is written as --. Several other languages use inc(x) and dec(x) functions. The increment operator increases, and the decrement operator decreases, the value of its operand by 1. The operand must have an arithmetic or pointer
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 ...
, and must refer to a modifiable
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 ...
. Pointers values are increased (or decreased) by an amount that makes them point to the next (or previous) element adjacent in memory. In languages that support both versions of the operators: * The ''pre''-increment and ''pre''-decrement operators increment (or decrement) their operand by 1, and the value of the expression is the resulting incremented (or decremented) value. * The ''post''-increment and ''post''-decrement operators increase (or decrease) the value of their operand by 1, but the value of the expression is the operand's value ''prior'' to the increment (or decrement) operation. In languages where increment/decrement is not an expression (e.g., Go), only one version is needed (in the case of Go, post operators only). Since the increment/decrement operator modifies its operand, use of such an operand more than once within the same expression can produce undefined results. For example, in expressions such as x - ++x, it is not clear in what sequence the subtraction and increment operations should be performed. Such expressions generally invoke
undefined behavior In computer programming, undefined behavior (UB) is the result of executing a program whose behavior is prescribed to be unpredictable, in the language specification to which the computer code adheres. This is different from unspecified behavior ...
, and should be avoided. In languages with typed pointers like C, the increment operator steps the pointer to the next item of that type -- increasing the value of the pointer by the size of that type. When a pointer (of the right type) points to any item in an array, incrementing (or decrementing) makes the pointer point to the "next" (or "previous") item of that array. When a pointer has a type of pointer-to-integer, incrementing that pointer makes it point to the next integer (typically increasing it by 4 bytes). When a pointer has a type pointer-to-employee, incrementing that pointer makes it point to the next "employee" -- if the size of the employee structure is 106 bytes, incrementing that pointer increases it by 106 bytes.


Examples

The following C code fragment illustrates the difference between the ''pre'' and ''post'' increment and decrement operators: int x; int y; // Increment operators // Pre-increment: x is incremented by 1, then y is assigned the value of x x = 1; y = ++x; // x is now 2, y is also 2 // Post-increment: y is assigned the value of x, then x is incremented by 1 x = 1; y = x++; // y is 1, x is now 2 // Decrement operators // Pre-decrement: x is decremented by 1, then y is assigned the value of x x = 1; y = --x; // x is now 0, y is also 0 // Post-decrement: y is assigned the value of x, then x is decremented by 1 x = 1; y = x--; // y is 1, x is now 0 In languages lacking these operators, equivalent results require an extra line of code: # Pre-increment: y = ++x x = 1 x = x + 1 # x is now 2 (can be written as "x += 1" in Python) y = x # y is also 2 # Post-increment: y = x++ x = 1 y = x # y is 1 x = x + 1 # x is now 2 The post-increment operator is commonly used with
array An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
subscripts. For example: // Sum the elements of an array float sum_elements(float arr[], int n) The post-increment operator is also commonly used with pointer (computer programming), pointers: // Copy one array to another void copy_array(float *src, float *dst, int n) Note that these examples also work in other C-like languages, such as
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 ...
,
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 ...
, and C#. *Increment operator can be demonstrated by an example: #include int main() **Output: 2 4


Supporting languages

The following list, though not complete or all-inclusive, lists some of the major programming languages that support the ++/-- increment/decrement operators. *
ABAP ABAP (Advanced Business Application Programming, originally ''Allgemeiner Berichts-Aufbereitungs-Prozessor'', German for "general report preparation processor") is a high-level programming language created by the German software company SAP SE. ...
*
AWK AWK (''awk'') is a domain-specific language designed for text processing and typically used as a data extraction and reporting tool. Like sed and grep, it is a filter, and is a standard feature of most Unix-like operating systems. The AWK lang ...
*
Bash Bash or BASH may refer to: Arts and entertainment * ''Bash!'' (Rockapella album), 1992 * ''Bash!'' (Dave Bailey album), 1961 * '' Bash: Latter-Day Plays'', a dramatic triptych * ''BASH!'' (role-playing game), a 2005 superhero game * "Bash" ('' ...
* C *
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 ...
* C# *
CFML ColdFusion Markup Language, more commonly known as CFML, is a scripting language for web development that runs on the JVM, the .NET framework, and Google App Engine. Multiple commercial and open source implementations of CFML engines are availab ...
* D * Go *
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 ...
*
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 Website, websites use JavaScript on the Client (computing), client side ...
*
Objective-C Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its NeXTS ...
*
GNU Octave GNU Octave is a high-level programming language primarily intended for scientific computing and numerical computation. Octave helps in solving linear and nonlinear problems numerically, and for performing other numerical experiments using a langu ...
*
PARI/GP PARI/GP is a computer algebra system with the main aim of facilitating number theory computations. Versions 2.1.0 and higher are distributed under the GNU General Public License. It runs on most common operating systems. System overview The ...
*
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 offici ...
*
PHP PHP is a general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by The PHP Group. ...
*
PowerShell PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell (computing), shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it ...
*
Vala Vala or VALA may refer to: Religion and mythology * Vala (Vedic), a demon or a stone cavern in the Hindu scriptures * Völva, also spelled Vala, a priestess in Norse mythology and Norse paganism Fiction * Vala (Middle-earth), an angelic being in ...
* Vex, a scripting language in the software Houdini *
Wolfram Language The Wolfram Language ( ) is a general multi-paradigm programming language developed by Wolfram Research. It emphasizes symbolic computation, functional programming, and rule-based programming and can employ arbitrary structures and data. It ...
(Apple's
Swift Swift or SWIFT most commonly refers to: * SWIFT, an international organization facilitating transactions between banks ** SWIFT code * Swift (programming language) * Swift (bird), a family of birds It may also refer to: Organizations * SWIFT, ...
once supported these operators, but support was removed as of version 3.) Pascal,
Delphi Delphi (; ), in legend previously called Pytho (Πυθώ), in ancient times was a sacred precinct that served as the seat of Pythia, the major oracle who was consulted about important decisions throughout the ancient classical world. The oracle ...
,
Modula-2 Modula-2 is a structured, procedural programming language developed between 1977 and 1985/8 by Niklaus Wirth at ETH Zurich. It was created as the language for the operating system and application software of the Lilith personal workstation. It w ...
, and
Oberon Oberon () is a king of the fairies in medieval and Renaissance literature. He is best known as a character in William Shakespeare's play ''A Midsummer Night's Dream'', in which he is King of the Fairies and spouse of Titania, Queen of the Fair ...
provide the same functions, but they are called inc(x) and dec(x). Notably
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 ...
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(OH ...
do not support these operators.


History

The concept was introduced in the B programming language circa 1969 by
Ken Thompson Kenneth Lane Thompson (born February 4, 1943) is an American pioneer of computer science. Thompson worked at Bell Labs for most of his career where he designed and implemented the original Unix operating system. He also invented the B programmi ...
.
Thompson went a step further by inventing the ++ and -- operators, which increment or decrement; their prefix or postfix position determines whether the alteration occurs before or after noting the value of the operand. They were not in the earliest versions of B, but appeared along the way. People often guess that they were created to use the auto-increment and auto-decrement address modes provided by the DEC PDP-11 on which C and Unix first became popular. This is historically impossible, since there was no PDP-11 when B was developed. The PDP-7, however, did have a few 'auto-increment' memory cells, with the property that an indirect memory reference through them incremented the cell. This feature probably suggested such operators to Thompson; the generalization to make them both prefix and postfix was his own. Indeed, the auto-increment cells were not used directly in implementation of the operators, and a stronger motivation for the innovation was probably his observation that the translation of ++x was smaller than that of x=x+1.


See also

*
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 ...
– for += and -= operators *
PDP-7 The PDP-7 was a minicomputer produced by Digital Equipment Corporation as part of the PDP series. Introduced in 1964, shipped since 1965, it was the first to use their Flip-Chip technology. With a cost of , it was cheap but powerful by the s ...
*
PDP-11 The PDP-11 is a series of 16-bit minicomputers sold by Digital Equipment Corporation (DEC) from 1970 into the 1990s, one of a set of products in the Programmed Data Processor (PDP) series. In total, around 600,000 PDP-11s of all models were sold, ...
* Successor function


References

{{Reflist Operators (programming) Unary operations