4
C Increment and Decrement Operators
Programs coded with short-hand operators can run several milliseconds faster. Same as increment and decrement operators. They are — (minus minus) and ++ (plus plus). The following example shows the usage of these two operators:
x = y + z++; // z is incremented by one after x was calculated x = y + --z; // Decrement z by one first, then calculate x
In the above example, if y = 2 and z = 4:
x = 2 + 4++ => x = 6 (z has become 5, x doesn’t change since it’s already calculated)
x = 2 + –4 => x = 2 + 3 => x = 5 (z first decremented to 3, and then calculates x)
As you can see, the position of the operator is very important.
Here is the sample code for these operators:
/*
* inDecrement.c
*
* Program to illustrate the use of the increment
* and decrement operators
*
* by Mark Virtue, 2001.
*
*/
#include <stdio.h>
main() {
int x, y, z = 1;
y = 5;
x = 6;
puts(""); // Prints out a new line
printf("Before: x = %d, y = %d, z = %dn", x, y, z);
z = x++ + ++y; // First y is incremented to 6, and then z gets calculated to 12. Lastly, x is incremented to 7
puts("");
puts("z = x++ + ++y");
printf("After: x = %d, y = %d, z = %dn", x, y, z);
puts("");
printf("Before: x = %d, y = %d, z = %dn", x, y, z);
z = x++ - --y; // Same format as above
puts("");
puts("z = x++ - --y");
printf("After: x = %d, y = %d, z = %dn", x, y, z);
fflush(stdin);
getchar();
}
And here is the output for the above code:
If you have any question regarding the increment and decrement operators, leave a comment below.
