Increment and Decrement Operators
Increment and Decrement Operators
Examples
The following C code fragment illustrates the difference between the pre and post increment and decrement operators: int int x; y;
// Increment operators x = 1; y = ++x; // x is now 2, y is also 2 y = x++; // x is now 3, y is 2 // Decrement operators x = 3; y = x--; // x is now 2, y is 3 y = --x; // x is now 1, y is also 1 The post-increment operator is commonly used with array subscripts. For example: // Sum the elements of an array float sum_elements(float arr[], int n) { float sum = 0.0; int i = 0;
Increment and decrement operators while (i < n) sum += arr[i++]; return sum; } Likewise, the post-increment operator is commonly used with pointers: // Copy one array to another using pointers void copy_array(float *src, float *dst, int n) { 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 increment/decrement operators.
C C++ C# D Go Java JavaScript Perl PHP AWK
License
Creative Commons Attribution-Share Alike 3.0 Unported //creativecommons.org/licenses/by-sa/3.0/