Post increment and Pre increment in C

Pkp picture Pkp · May 26, 2012 · Viewed 7.3k times · Source

I have a question about these two C statements:

  1. x = y++;

  2. t = *ptr++;

With statement 1, the initial value of y is copied into x then y is incremented.

With statement 2, We look into the value pointed at by *ptr, putting that into variable t, then sometime later increment ptr.

For statement 1, the suffix increment operator has higher precedence than the assignment operator. So shouldn't y be incremented first and then x is assigned to the incremented value of y?

I'm not understanding operator precedence in these situations.

Answer

Jerry Coffin picture Jerry Coffin · May 26, 2012

You're mistaken about the meaning of your 2]. Post-increment always yields the value from before the increment, then sometime afterward increments the value.

Therefore, t = *ptr++ is essentially equivalent to:

t = *ptr;
ptr = ptr + 1;

The same applies with your 1] -- the value yielded from y++ is the value of y before the increment. Precedence doesn't change that -- regardless of how much higher or lower the precedence of other operators in the expression, the value it yields will always be the value from before the increment, and the increment will be done sometime afterwards.