'op=' operators
pcf at drux3.UUCP
pcf at drux3.UUCP
Fri Oct 5 02:13:18 AEST 1984
> I am not sure how K&R specify that
> *ptr++ += 2;
> should be evaluated. Page 191 says only that the behaviour of E1 op= E2
> is the same as E1 = E1 op E2, ...
> Robert
Are you sitting comfortably, then I'll begin. Once upon a time...
Some quotes from the good book: (K&R 'C')
Page 187
When postfix ++ is applied to an lvalue the result is the value of the
object referred to by the lvalue. After the result is noted, the object is
incremented in the same manner as for the prefix ++ operator.
Page 191:
The behavior of an expression of the form E1 op= E2 may be inferred by tak-
ing it as eqivalent to E1 = E1 op (E2); however, E1 is only evaluated once.
We now have enough information to work it out.
*ptr++ += 2;
The expression on the right is evaluated (once),
E1 = *ptr++;
its value is the thing pointed to before the increment (*ptr). This value is
then (effectively) substituted in the expression
E1 = E1 + (2);
*ptr = *ptr + 2; ptr++;
Easy.
Now the encore:
Page 185:
...the order of evaluation of expressions is undefined. In particular the
compiler considers itself free to compute subexpressions in the order it
believes most efficient, even if the subexpressions involve side effects.
And remember that assignment operators are just operators, this means that
*ptr++ = *ptr++ + 2;
*ptr = *ptr++ + 2;
*ptr++ = *ptr++ + 2;
are all wrong. Correct versions include:
*ptr++ += 2;
*ptr += 2; ptr++;
Peter C. Fry
drux3!pcf
More information about the Comp.lang.c
mailing list