coperatorspost-incrementpre-increment

Priority operators in C


I found this text (source: https://education.cppinstitute.org/) and I'm trying to understand the second instruction.

Can you answer the question of what distinguishes these two instructions?

 c = *p++;

and

 c = (*p)++;

We can explain: the first assignment is as if the following two disjoint instructions have been performed;

 c = *p;
 p++;

In other words, the character pointed to by p is copied to the c variable; then, p is increased and points to the next element of the array.

The second assignment is performed as follows:

 c = *p;
 string[1]++;

The p pointer is not changed and still points to the second element of the array, and only this element is increased by 1.

What I don't understand is why it is not incremented when the = operator has less priority than the ++ operator.


Solution

  • With respect to this statement expression

    c = (*p)++;
    

    , you say

    What i dont understand is why [p] is not incremented when the = operator has less priority than the ++ operator.

    There is a very simple explanation: p is not incremented as a result of evaluating that expression because it is not the operand of the ++ operator.

    That is in part exactly because the = operator has lower precedence: because the precedence of = is so low, the operand of ++ is the expression (*p) rather than the expression c = (*p). Note in particular that p itself is not even plausibly in the running to be the operand in that case, unlike in the variation without parentheses.

    Moving on, the expression (*p) designates the thing to which p points, just as *p all alone would do. Context suggests that at that time, that's the same thing designated by string[1]. That is what gets incremented, just as the text says, and its value prior to the increment is the result of the postfix ++ operation.