Search code examples
coperator-precedenceassociativity

In which precedence is this statement evaluated?


++*P--;

That is a question from an exam, if P a pointer to any element in an array, explain what this statement really does.

I even wrote a simple code to evaluate it:

  int i;
    int* array = calloc(10, sizeof(int));
    for (i = 0; i < 10; i++) {
        array[i] = i;
        printf("%d,", array[i]);
    }
    int* P = array + 5;
    printf("\n %p", P);
    printf("\n %d", *P);

    ++*P--;
    printf("\n %p", P);
    printf("\n %d \n", *P);
    for (i = 0; i < 10; i++) {
        printf("%d,", array[i]);
    }

But the output confuses me even more:

0,1,2,3,4,5,6,7,8,9,
 0x100105534
 5
 0x100105530
 4 
0,1,2,3,4,6,6,7,8,9,

It looks like it first dereferences P, then increases its value and then decreases value of pointer P, but why?

According to K&R table 2-1 from p53 (see the picture below) ++, --, and * (dereference) has the same precedence and associativity from right to left. So first step should be decreasing value of P, then dereference and then increasing dereferenced value, am I wrong?

enter image description here


Solution

  • You are correct that the precedence is

    ++(*(P--))
    

    But note that the decrement is a postfix operation: even though the change to P happens first, the rest of the expression uses the old value of P. So in your example, first P is decremented to array+4, but the value of P-- is array+5, so array[5] gets incremented.