Search code examples
cpointersassignment-operatororder-of-execution

Arithmetic Pointers referencing same addresses


I'm struggling a bit to understand the following operation :

B is variable, Pt1 and Pt2 are pointing to &B

enter image description here

The decrement is done after the affectation, so with my logic it should be 68 but my IDE gives me 69, can someone explain ?

Thanks in advance.


Solution

  • The code you have given creates undefined behaviour! Taking away the pointer aspect, you are essentially doing this:

    B = B--;
    

    This cannot be consistently resolved, because you are assigning B the value of 69 and then post-decrementing B. So, which gives the answer: the assignment or the post-decrement?

    With your platform/IDE, the compiler has done something like this, using a 'temporary' variable:

    // Initial value of B is 69
    temp = B--; // temp is 69 and B is now 68
    B = temp;   // B now has the value of 69!
    

    However, you cannot rely on this 'interpretation' - either across different compilers, or even using similar code at different places with the same compiler!

    PS: Incidentally, you should post code as text, formatted as a code-block.