Chang May
Chang May

Reputation: 165

C++ Operator priority =, * and ++

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?

Upvotes: 1

Views: 1757

Answers (3)

James Kanze
James Kanze

Reputation: 154007

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.

Upvotes: 0

Brian Bi
Brian Bi

Reputation: 119457

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++))

Upvotes: 3

gsamaras
gsamaras

Reputation: 73414

Because they are post-fix operators, not pre-fix!

Upvotes: 2

Related Questions