6

Can anyone explain me the output.

#include<stdio.h>
int main() {
    int a[]={10,20,30};
    int *p=a;
    ++*p++;
    printf("%d  %d  %d  %d",*p,a[0],a[1],a[2]);
}

output is 20 11 20 30

Postfix incrementation has a higher precedence, so value of second index should have been incremented. Why is the value of first index incremented?

mlwn
  • 1,156
  • 1
  • 10
  • 25
Shubham Khare
  • 171
  • 1
  • 1
  • 12
  • 3
    Why is this marked as duplicate? `p` and `*p` are *separate objects*, so the arguments about undefined behavior in the supposedly duplicate question don't apply. – EOF Aug 04 '15 at 16:20
  • Because postfix increment binds more tightly than dereference . – rici Aug 04 '15 at 16:22
  • 3
    But I would not advise to use such a constructs for any purposes except educational ones.. – Eugene Sh. Aug 04 '15 at 16:37

2 Answers2

14

Due to operator precedence,

++*p++ is same as ++(*(p++)).

That is equivalent to:

int* p1 = p++; // p1 points to a[0], p points to a[1]
++(*p1);       // Increments a[0]. It is now 11.

That explains the output.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

This is because the postfix operator returns the value before the increment. So the pointer is well incremented but the prefix operator still applies to the original pointer value.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177