Programming in C

(Barry) #1
Pointers and Arrays 269

just seen, if xis a pointer to an array, this has the effect of setting xto point to the next
element of the array.
The increment and decrement operators can be used in expressions in which other
operators also appear. In such cases, it becomes important to know more precisely how
these operators work.
So far, when you used the increment and decrement operators, you always placed
them beforethe variables that were being incremented or decremented. So, to increment
a variable i,you simply wrote


++i;


Actually, it also is perfectly valid to place the increment operator afterthe variable, as fol-
lows:


i++;


Both expressions are perfectly valid and both achieve the same result—namely, of incre-
menting the value of i. In the first case, where the ++is placed before its operand, the
increment operation is more precisely identified as a preincrement. In the second case,
where the ++is placed after its operand, the operation is identified as a postincrement.
The same discussion applies to the decrement operator. So the statement


--i;


technically performs a predecrementof i, whereas the statement


i--;


performs a postdecrementof i. Both have the same net result of subtracting 1 from the
val ue of i.
It is when the increment and decrement operators are used in more complex expres-
sions that the distinction between the pre-and post-nature of these operators is realized.
Suppose you have two integers called iand j. If you set the value of ito 0 and then
write the statement


j = ++i;


the value that gets assigned to jis 1 ,and not 0 as you might expect. In the case of the
preincrement operator, the variable is incremented beforeits value is used in the expres-
sion. So, in the preceding expression, the value of iis first incremented from 0 to 1 and
then its value is assigned to j, as if the following two statements had been written
instead:


++i;
j = i;


If you instead use the postincrement operator in the statement


j = i++;

Free download pdf