what is the difference between *y++
and ++*y
?
The meaning of an expression in C is characterized by two things: what value it produces and what side effects it produces.
Let's examine the first expression.
Postfix increment is of higher priority than dereferencing, so this is *(y++)
.
The postfix increment produces a side effect: it changes the value of y
to point to a different location. The postfix increment also produces a value: the value that y
had before it was incremented. The *
operator then dereferences that value to produce an lvalue: that is, something you can use as a variable, either to store to or to fetch from.
I note that the side effect can happen at any point before or after the dereferencing. If you said
q = *y++
then the side effect of the ++
could happen at any point. This could be:
q = *y;
y = y + 1;
or it could be treated as
t = y;
y = y + 1;
q = *t;
Both are perfectly legal. (Except of course that if y
is itself an expression with side effects, those side effects must be produced only once. For clarity, I'll make that assumption throughout.)
How about ++*y
? That is straightforward: *y
produces a variable, the content of the variable is incremented, and the value of the expression is the incremented value. Note that again, the side effect can be produced out-of-order:
q = ++*y
could be treated as:
t = *y + 1;
*y = t;
q = t;
or as
t = *y + 1;
q = t;
*y = t;
Remember, C does not produce very many restrictions on the order in which side effects may happen, so be careful.