helpdesk
helpdesk

Reputation: 2084

precedence and associatives in C

In a code segment, I saw this uncompacted form :

while(p1>=str1)
 {
  *p2 = *p1;
  p1--;
  p2++;
}

while the compacted form looks something like this :

 while(p1>=str1)
 {
   *p2++ = *p1--;
 }

what the code does is like clearly shown in the uncompacted form, it first copies the contents of the pointers before incrementing the p2 and decrementing the p1 but how could that be given that the ++ precedence is higher than the assignment operator in C? I thought there could be some () operator to force this but in the book it is correct. Can anyone explain this ? Thanks

Upvotes: 0

Views: 86

Answers (3)

JAB
JAB

Reputation: 21089

The ++ and -- postfix operators take effect after the statement they are included in is performed. The precedence affects how tokens are grouped and how the syntax tree (I'm probably using the wrong vocabulary here) for the statement is generated.

Basically, *p2++ = *p1--; is equivalent to *p2 = *p1; p2 += 1; p1 -= 1;

Do be careful with the post- and prefix operators, though; doing something like p2 = p1++ * p1--; is considered undefined behavior, I believe.

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375932

The precedence simply affects how the code is parsed, that is, what the ++ refers to. That why this:

*p2++ = *p1--;

is equivalent to this:

(*(p2++)) = (*(p1--));

But the semantics of ++ are to evaluate to the original value, and then later to increment the value. So the assignment will use the old values of p1 and p2, and then after the assignment is performed, will increment and decrement them.

Upvotes: 3

ouah
ouah

Reputation: 145899

p2++ expression yields the value of p2 and not p2 + 1. The increment operation is done a the sequence point.

Upvotes: 1

Related Questions