Page 46 - Programming Microcontrollers in C
P. 46
Increment and Decrement Operators 31
Here the i value stored in memory is replaced by one more than the
value found there at the beginning of execution of the expression.
The C expression
++i;
will do exactly the same thing. The increment operator ++ causes 1
to be added to the value in the memory location i. The decrement
operator -- causes 1 to be subtracted from the value in the memory
location. The increment and decrement operators can be either pre
fix or postfix operators. If, like above, the ++ operator precedes the
variable, it is called a prefix operator. If the variable is used in an
expression, it will be incremented prior to its use. For example, sup
pose i = 5. Then the expression
j = 2 * ++i;
will leave a 12 for the value j and 6 for i. On the other hand, if i
again is 5, the expression
j = 2 * i--;
will leave a value of 10 for j and 4 for I.
An easy way to see how the preincrement and the postincrement
works is as follows: Suppose that you have a pair of statements
j=j+1;
<statement with j>
These statements can be replaced with
<statement with ++j>
The preincrement means that you should replace j with j+1 before
you evaluate the expression. Likewise the statements
<statement with j>
j=j+1;
can be replaced with
<statement with j++>
with the post increment, you should evaluate the expression and then
replace j with j+1.