问题
I have a question with this pointer value assignment:
*p++ = *q++;
According to Operator Priority Table
The priorities of operators are "++" > "*" > "=".
But the result of the above statement does the assignment "=" first, as the following
*p = *q;
p++;
q++;
Why?
回答1:
The post-increment operator increments its operand after its value has already been computed. The pointer dereference therefore occurs on the values the pointers held before this line. However, the precedence you give is correct; the expression is indeed equivalent to
(*(p++)) = (*(q++))
回答2:
Because they are post-fix operators, not pre-fix!
回答3:
You're missing an important distinction. An operator has a value, and
it may have side effects. In the case of postfix ++
, the value is the
value before the incrementation, and the side effect is thhe
incrementation. What is used in the expression is the value. The side
effects may occur at any time before the end of the full expression (in
pre-C++11 terms, but the actual effect hasn't changed); a compiler might
start by incrementing the two pointers, saving their previous values in
registers and using them in the rest of the expression, or by using the
values directly from memory, and deferring the incrementation of both
pointers until the end of the expression. Or any combination of
operations which results in the same observable behavior.
来源:https://stackoverflow.com/questions/27850172/c-operator-priority-and