Search code examples
cpointersexpressionoperator-precedencesequence-points

Confusing answers : One says *myptr++ increments pointer first,other says *p++ dereferences old pointer value


I would appreciate if you clarify this for me.Here are two recent questions with their accepted answers:

1) What is the difference between *myptr++ and *(myptr++) in C

2) Yet another sequence point query: how does *p++ = getchar() work?

The accepted answer for the first question,concise and easily to understand states that since ++ has higher precedence than *, the increment to the pointer myptr is done first and then it is dereferenced.I even checked that out on the compiler and verified it.

But the accepted answer to the second question posted minutes before has left me confused.

It says in clear terms that in *p++ strictly the old address of p is dereferenced. I have little reason to question the correctness of a top-rated answer of the second question, but frankly I feel it contradicts the first question's answer by user H2CO3.So can anyone explain in plain and simple English what the second question's answer mean and how come *p++ dereferences the old value of p in the second question.Isn't p supposed to be incremented first as ++ has higher precedence?How on earth can the older address be dereferenced in *p++Thanks.


Solution

  • The postfix increment operator does have higher precedence than the dereference operator, but postfix increment on a variable returns the value of that variable prior to incrementing.

    *myptr++
    

    Thus the increment operation has higher precedence, but the dereferencing is done on the value returned by the increment, which is the previous value of myptr.


    The answer in the first question you've linked to is not wrong, he's answering a different question.

    There is no difference between *myptr++ and *(myptr++) because in both cases the increment is done first, and then the previous value of myptr is dereferenced.