Programming in C

(Barry) #1

270 Chapter 11 Pointers


then iis incremented afterits value has been assigned to j.So,if iis 0 before the pre-
ceding statement is executed, 0 is assigned to jand theniis incremented by 1, as if the
statements
j = i;
++i;
were used instead. As another example, if iis equal to 1, then the statement
x = a[--i];
has the effect of assigning the value of a[0]to xbecause the variable iis decremented
before its value is used to index into a.The statement
x = a[i--];
used instead has the effect of assigning the value of a[1]to xbecause iis decremented
after its value has been used to index into a.
As a third example of the distinction between the pre- and post- increment and
decrement operators, the function call
printf ("%i\n", ++i);
increments iand then sends its value to the printffunction, whereas the call
printf ("%i\n", i++);
increments iafter its value has been sent to the function. So, if iis equal to 100, the first
printfcall displays 101, whereas the second printfcall displays 100. In either case, the
val ue of iis equal to 101 after the statement has executed.
As a final example on this topic before presenting Program 11.14, if textPtris a
character pointer, the expression
*(++textPtr)
first increments textPtrand then fetches the character it points to, whereas the
expression
*(textPtr++)
fetches the character pointed to by textPtrbefore its value is incremented. In either
case, the parentheses are not required because the *and ++operators have equal prece-
dence but associate from right to left.
Now go back to the copyStringfunction from Program 11.13 and rewrite it to
incorporate the increment operations directly into the assignment statement.
Because the toand frompointers are incremented each time after the assignment
statement inside the forloop is executed, they should be incorporated into the assign-
ment statement as postincrement operations.The revised forloop of Program 11.13
then becomes
for ( ; *from != '\0'; )
*to++ = *from++;
Free download pdf