Search code examples
cpointersoperator-precedencepost-increment

Order of Evaluation in C Operators


As per C, PostIncrement(a++) > Dereference(*) > Assignment(=) When I execute this below c snippet,

#include <stdio.h>

int main(){

    int arr[]= {1,2,3};
    int *p = a;

    *p++ = 3;

    for(int i=0;i<3;i++){
        printf("%d ",arr[i]);  
    }

}

Output: 3 2 3

But if we apply order of precedence in this statement,

 *p++ = 3;

The statement will be evaluated in the following order:

  1. p++ will be evaluated
  2. *p will get dereferenced.
  3. then 3 will be assigned to *p using the assignment operator

If we apply the above order, p which is pointing to the start of the array arr, will get incremented first and point to the second element of the array. Then second element's address will get dereferenced and then 3 will be assigned to the second index. So our expected output should be 1 3 3 But the output I got is 3 2 3.

I know that my expected output is not correct. It'll be helpful if you explain the order of evaluation here in this case of the output of the compiler.


Solution

  • The result of a post-increment expression is the value of the operand before it is incremented. Thus, even though the ++ in *p++ does, indeed, have higher precedence than the *, the latter is applied to the result of the p++ expression which is, as just mentioned, the initial value of p.