C++ Operator priority =, * and ++

浪子不回头ぞ 提交于 2019-12-24 14:22:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!