Search code examples
cprogramming-languages

Doubt in usage of *++p in printf


int main(){
    int a[3]={1,10,20};
    int *p=a;
    printf("%d %d " ,*++p,*p);
    return 0;
}

The output to the code above is 10 1 on a gcc compiler.

I understand that *++p increments p and dereferences the new value. But since p has been incremented, why does *p return 1 instead of 10?


Solution

  • It's unspecified behaviour in what order function argument expressions are evaluated. Some compilers might use left-to-right, some right-to-left, and some might do a different evaluation order depending on the situation for optimalization. So in your case *p gets evaluated before *++p which results in your "weird output".