C22. C Increment and Decrement Operators


Increment and Decrement Operators
Two of the most common operations on a variable are “incrementing” (adding 1) and “decrementing” (subtracting 1). We can, of course, accomplish these tasks by writing
i = i + 1;
 j = j - 1;
The compound assignment operators allow us to condense these statements a bit:
i += 1;
 j   > l;
But C allows increments and decrements to be shortened even further, using the ++ (increment) and - - {decrement) operators.
At first glance, the increment and decrement operators are simplicity itself: ++ adds 1 to its operand, whereas - - subtracts 1. Unfortunately, this simplicity is mis­leading  >the increment and decrement operators can be tricky to use. One compli­cation is that ++ and    can be used as prefix operators (++i and   i, for example) or postfix operators (i++ and i- -). The correctness of a program may hinge on picking the proper version.
Another complication is that, like the assignment operators. ++ and    have side effects: they modify the values of their operands. Evaluating the expression ++i (a “pre-increment”) yields i + 1 and  >as a side effect  >increments i.

No comments: