Debaser said:
I was surprised to learn in class today that given a pointer p, the
statement:
*p++;
dereferences first and then increments the pointer.
That's incorrect. There's no such thing as "first" and "then" in this
case. Relative precedence of operators '*' and post-'++' means only one
thing: '++' applies to 'p' and '*' applies to the result of 'p++', which
is the original value of 'p'. The only requirement that must be
satisfied is that these operators receive these correct values as
parameters. Which one will be applied first in this case is absolutely
unpredictable.
So say p points to
an array location array[4]. During execution p would be dereferenced
and THEN increment p to point to array[5].
No. Not necessarily. It can be done the way you describe. Or it can be
done in completely opposite order. For example, 'p' could be incremented
first, and only then the old value of 'p' (previously stored somewhere)
could be dereferenced.
Our professor says that
when operators have equal precedence, you read from right to left.
That's correct. But the important thing your professor didn't seem to
tell you is that precedence only defines the grouping of operators and
their operands. It does not define the temporal ordering of operations.
So
I'm left wondering, what is the rule for determining when exactly a
post-increment executes?
As long as you are dealing with built-in operators, there's no such
rule. In C++ language two actions are ordered in time if and only if
they are separated by at least one sequence point. Actions that are not
separated by sequence points can be executed in arbitrary order (as long
as their semantics remains unchanged). Expression '*p++' has no sequence
points inside, which means that nothing can be said about what happens
"first" and what happens "second".
What if it were the statement:
*(p++);
Same thing?
Yes, exactly the same thing. Parentheses affect grouping of operators
and their operands. They have no effect on the order of operations.
Read about sequence points and remember a simple rule: no sequence point
- no ordering.