-3
#include <stdio.h>

int main()
{
   int i[ ] = {3, 5};
   int *p = i;
   int j = --*p++;   

   printf("j = %d\n\n", j);

   return 0;
}

Can someone explain to me why the answer is "j = 2"?

This code from the course notebook; they didn't explain it in the book.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Xannie21
  • 13
  • 2
  • 2
    What else would you expect it to be, and why? – Siguza Mar 24 '18 at 17:30
  • 1
    One thing to learn here is never to do things like `--*p++`. There is absolutely no reason to write code like that, except *possibly* to confuse newbies. – Bo Persson Mar 24 '18 at 20:35

1 Answers1

0

This behavior can be described as operator precedence and it's something to do with how C compiler processed your code. In this case, the postfixed ++ operator takes precedence over * operator and incremented the pointer-to-array after you decremented the value of the dereferenced pointer with prefixed --, safe to say it's similarly written as such:

int main()
{
    int i[ ] = {3, 5};
    int *p = i;
    int j = --(*p++);   

    printf("j = %d\n\n", j);

    return 0;
} 

References:

ionizer
  • 1,661
  • 9
  • 22