Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output of ++*p++

Tags:

c

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?

like image 657
Shubham Khare Avatar asked Aug 04 '15 16:08

Shubham Khare


2 Answers

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.

like image 74
R Sahu Avatar answered Oct 07 '22 12:10

R Sahu


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.

like image 44
Jens Gustedt Avatar answered Oct 07 '22 12:10

Jens Gustedt