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}

Note that 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/decrement operators.

(Apple's Swift once supported these operators, [12] but support was removed as of version 3.)

Pascal, Delphi, Modula-2, and Oberon provide the same functions, but they are called inc(x) and dec(x).

Notably Python and Rust do not support these operators.

History

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

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

Brainfuck is an esoteric programming language created in 1993 by Urban Müller.

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, protocol stacks, though decreasingly for application software. 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 called 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 infinite 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, an 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 maybe 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.

The syntax of the C programming language is the set of rules governing writing of software in the C language. 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.

<span class="mw-page-title-main">Pointer (computer programming)</span> Object which stores memory addresses in a computer program

In computer science, a pointer is an object in many programming languages that stores a memory address. This can be that of another value located in computer memory, or in some cases, that of memory-mapped computer hardware. A pointer references a location in memory, and obtaining the value stored at that location is known as dereferencing the pointer. As an analogy, a page number in a book's index could be considered a pointer to the corresponding page; dereferencing such a pointer would be done by flipping to the page with the given page number and reading the text found on that page. The actual format and content of a pointer variable is dependent on the underlying computer architecture.

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.

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.

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.

<span class="mw-page-title-main">C data types</span> Data types supported by the C programming language

In the C programming language, data types constitute the semantics and characteristics of storage of data elements. They are expressed in the language syntax in form of declarations for memory locations or variables. Data types also determine the types of operations or methods of processing of data elements.

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

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 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.
  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. "Basic Operators". developer.apple.com.
  13. Ritchie, Dennis M. (March 1993). "The Development of the C Language". ACM SIGPLAN Notices. 28 (3): 5. doi: 10.1145/155360.155580 .