Increment and decrement operators

Last updated

Increment and decrement operators are unary operators that increase or decrease their operand by one.

Contents

They are commonly found in imperative programming languages. 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, and must refer to a modifiable data object. 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:

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, 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. Thus, incrementing a pointer to an integer makes it point to the next integer (typically increasing the pointer value by 4); [1] incrementing a pointer to a structure of size 106 bytes makes it point to the next structure by increasing the pointer value by 106. [2]

Examples

The following C code fragment illustrates the difference between the pre and post increment and decrement operators:

intx;inty;// Increment operators// Pre-increment: x is incremented by 1, then y is assigned the value of xx=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 1x=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 xx=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 1x=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 = ++xx=1x=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=1y=x# y is 1x=x+1# x is now 2


The post-increment operator is commonly used with array subscripts. For example:

// Sum the elements of an arrayfloatsum_elements(floatarr[],intn){floatsum=0.0;inti=0;while(i<n)sum+=arr[i++];// Post-increment of i, which steps//  through n elements of the arrayreturnsum;}

The post-increment operator is also commonly used with pointers:

// Copy one array to anothervoidcopy_array(float*src,float*dst,intn){while(n-->0)// Loop that counts down from n to zero*dst++=*src++;// Copies element *(src) to *(dst),//  then increments both pointers}

These examples also work in other C-like languages, such as C++, Java, and C#.

Supporting languages

The following list, though not complete or all-inclusive, lists some of the major programming languages that support the increment and decrement operators.

Apple's Swift once supported these operators, but it's been depreciated since version 2.2 [13] and removed as of version 3.0. [14]

Pascal, Delphi, Modula-2, and Oberon uses functions (inc(x) and dec(x)) instead of operators.

Notably Python and Rust do not support these operators.

History

The concept was introduced in the B programming language circa 1969 by Ken Thompson. [15]

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

Related Research Articles

C is a general-purpose computer programming language. It was created in the 1970s by Dennis Ritchie, and remains very widely used and influential. By design, C's features cleanly reflect the capabilities of the targeted CPUs. It has found lasting use in operating systems, device drivers, and protocol stacks, but its use in application software has been decreasing. C is commonly used on computer architectures that range from the largest supercomputers to the smallest microcontrollers and embedded systems.

In logic, mathematics, and computer science, arity is the number of arguments or operands taken by a function, operation or relation. In mathematics, arity may also be called rank, but this word can have many other meanings. In logic and philosophy, arity may also be called adicity and degree. In linguistics, it is usually named valency.

A one-instruction set computer (OISC), sometimes referred to as an ultimate reduced instruction set computer (URISC), is an abstract machine that uses only one instruction – obviating the need for a machine language opcode. With a judicious choice for the single instruction and given arbitrarily many resources, an OISC is capable of being a universal computer in the same manner as traditional computers that have multiple instructions. OISCs have been recommended as aids in teaching computer architecture and have been used as computational models in structural computing research. The first carbon nanotube computer is a 1-bit one-instruction set computer.

In mathematics, a unary operation is an operation with only one operand, i.e. a single input. This is in contrast to binary operations, which use two operands. An example is any function f : AA, where A is a set. The function f is a unary operation on A.

In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral at the level of its individual bits. It is a fast and simple action, basic to the higher-level arithmetic operations and directly supported by the processor. Most bitwise operations are presented as two-operand instructions where the result replaces one of the input operands.

<span class="mw-page-title-main">Index register</span> CPU register used for modifying operand addresses

An index register in a computer's CPU is a processor register used for pointing to operand addresses during the run of a program. It is useful for stepping through strings and arrays. It can also be used for holding loop iterations and counters. In some architectures it is used for read/writing blocks of memory. Depending on the architecture it may be a dedicated index register or a general-purpose register. Some instruction sets allow more than one index register to be used; in that case additional instruction fields may specify which index registers to use.

<span class="mw-page-title-main">C syntax</span> Set of rules defining correctly structured programs

The syntax of the C programming language is the set of rules governing writing of software in C. It is designed to allow for programs that are extremely terse, have a close relationship with the resulting object code, and yet provide relatively high-level data abstraction. C was the first widely successful high-level language for portable operating-system development.

This is a list of operators in the C and C++ programming languages. All the operators listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.

In computer programming, the ternary conditional operator is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, ternary if, or inline if. An expression a ? b : c evaluates to b if the value of a is true, and otherwise to c. One can read it aloud as "if a then b otherwise c". The form a ? b : c is by far and large the most common, but alternative syntaxes do exist; for example, Raku uses the syntax a ?? b !! c to avoid confusion with the infix operators ? and !, whereas in Visual Basic .NET, it instead takes the form If(a, b, c).

Addressing modes are an aspect of the instruction set architecture in most central processing unit (CPU) designs. The various addressing modes that are defined in a given instruction set architecture define how the machine language instructions in that architecture identify the operand(s) of each instruction. An addressing mode specifies how to calculate the effective memory address of an operand by using information held in registers and/or constants contained within a machine instruction or elsewhere.

In computer programming, operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically.

A struct in the C programming language is a composite data type declaration that defines a physically grouped list of variables under one name in a block of memory, allowing the different variables to be accessed via a single pointer or by the struct declared name which returns the same address. The struct data type can contain other data types so is used for mixed-data-type records such as a hard-drive directory entry, or other mixed-type records.

The computer programming languages C and Pascal have similar times of origin, influences, and purposes. Both were used to design their own compilers early in their lifetimes. The original Pascal definition appeared in 1969 and a first compiler in 1970. The first version of C appeared in 1972.

sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of char-sized units. Consequently, the construct sizeof (char) is guaranteed to be 1. The actual number of bits of type char is specified by the preprocessor macro CHAR_BIT, defined in the standard include file limits.h. On most modern computing platforms this is eight bits. The result of sizeof has an unsigned integer type that is usually denoted by size_t.

The conditional operator is supported in many programming languages. This term usually refers to ?: as in C, C++, C#, and JavaScript. However, in Java, this term can also refer to && and ||.

In computer programming, an anonymous function is a function definition that is not bound to an identifier. Anonymous functions are often arguments being passed to higher-order functions or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function. Anonymous functions are ubiquitous in functional programming languages and other languages with first-class functions, where they fulfil the same role for the function type as literals do for other data types.

In computer science, a type punning is any programming technique that subverts or circumvents the type system of a programming language in order to achieve an effect that would be difficult or impossible to achieve within the bounds of the formal language.

In the C and C++ programming languages, the comma operator is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value ; there is a sequence point between these evaluations.

The syntax and semantics of PHP, a programming language, form a set of rules that define how a PHP program can be written and interpreted.

In the C programming language, operations can be performed on a bit level using bitwise operators.

References

  1. Richard M Reese. "Understanding and Using C Pointers". "Chapter 4. Pointers and Arrays". O'Reilly Media, Inc. 2013. ISBN   9781449344184
  2. Richard Petersen. "Introductory C with C++". 2019. Figure 12-12.
  3. "GNU Awk's User Guide". Free Software Foundation.
  4. "8.3. The Double-Parentheses Construct". The Linux Documentation Project.
  5. Ritchie, Brian W. Kernighan; Dennis M.; Ritchie, Dennis (1988). The C programming language (2. ed., [Nachdr.] ed.). Englewood Cliffs, N.J.: Prentice Hall. p.  18. ISBN   0-13-110362-8.{{cite book}}: CS1 maint: multiple names: authors list (link)
  6. "Increment/decrement operators". cppreference.com.
  7. "++ Operator (C# Reference)". Microsoft Developer Network.
  8. "Operator Overloading". dlang.org.
  9. "GP Operators and their Priorities".
  10. "About Assignment Operators".
  11. "Increment Wolfram Language Symbol". Wolfram Language Documentation Center.
  12. "Decrement Wolfram Language Symbol". Wolfram Language Documentation Center.
  13. "New Features in Swift 2.2". Swift Official Website.
  14. "Swift 3.0 Released!". Swift Official Website.
  15. Ritchie, Dennis M. (March 1993). "The Development of the C Language". ACM SIGPLAN Notices. 28 (3): 5. doi: 10.1145/155360.155580 .