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 subscripts. For example: // Sum the elements of an array float sum_elements(float arr[], int n) { float sum = 0.0; int i = 0; while (i The post-increment operator is also commonly used with
pointers: // Copy one array to another 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 } These examples also work in other C-like languages, such as
C++,
Java, and
C#. • Increment operator can be demonstrated by an example: • include int main() { int c = 2; printf("%d\n", c++); // this statement displays 2, then c is incremented by 1 to 3. printf("%d", ++c); // this statement increments c by 1, then c is displayed. return 0; } • Output: 2 4 ==Supporting languages==