Does *p++ increment after dereferencing?
Try it. The program
#include <stdio.h>
int main(void) {
int p[2];
int *q = p;
p[0] = 10;
p[1] = 100;
printf("%d\n", *q++);
printf("%d\n", *q);
return 0;
}
prints
10
100
showing that the ++
applies to p
, not to *p
, and that the increment happens after the dereference.
EDIT: (Thanks to @EricLippert for convincing me to pull out K & R)
Not only may there be a happens-after relationship, but according to K & R page 203, there must be:
A postfix expression followed by a ++ or -- operator is a postfix expression. The value of the expression of the expression is the value of the operand. After the value is noted, the operand is incremented (++) or decremented (--) by 1.
(emphasis mine)
Granted, I don't believe that K & R says anything about the semantics of C in the presence of multithreading (according to Wikipedia the pthreads specification was released in 1995), but for a single-threaded program K & R is pretty clear.
In the operators table, you can see that the suffix operator ++
have higher place than the *
unary operator.
Hence, *p++
increase p
(and not *p
), and return the value of the address that p
contained before the increment (since it's the suffix ++
).
But the order is implementation-depend. It may begin by dereferencing p, and then increase it, and it may store the old value of p
, increase it, and then dereference the old value.
There is no ordering between the increment and the dereference. However, the *
operator applies to the result of p++
, which is the original value of p
prior to the increment.