why does post increment doesn't work but pre increment works?

62 Views Asked by At

You can look at the code below and notice that last two outputs should be same as we have increased the value stored in tempptr which is addredd of temp using dblptr. It works when we do pre increment but doesn't work if we do post increment. Can someone explain this.

int main(){
    int temp=10;
    int * tempptr= &temp;
    int ** dblptr= &tempptr;

    cout<<tempptr<<endl;
    cout<<*(dblptr)<<endl;
    
    ++ *(dblptr);         //pre//
    // *(dblptr) ++;      //post//
    
    cout<<tempptr<<endl;
    cout<<*(dblptr)<<endl;
    
    return 0;
}

I am expecting last two outputs to be same. Because even though after the (pre or post) works differently they do same thing at last that is ++a or a++ becomes a=a+1 after execution. Like ex.

int a=2;
int j;
j=a++;

j becomes 2 and then a is incremented.

or

j=++a;

j becomes 3 and even the a is 3.

Meaning after the execution of line value of a becomes 3.

2

There are 2 best solutions below

0
user7860670 On

Post increment has higher precedence than dereference so without proper parenthesis placement you increment dblptr itself, making it point past tempptr and leading to Undefined Behavior when dereferencing it while printing second time.

You need to fix computation order with parenthesis: (* (dblptr)) ++;

Also wrapping (dblptr) in parenthesis in this code makes no sense.

1
tbxfreeware On

why does post increment doesn't work but pre increment works?

Check the operator precedence chart.

Post-fix increment has higher precedence than pointer dereference, so, *(dblptr) ++ is the same as *((dblptr) ++). What you want, I presume, is (*(dblptr)) ++.

Prefix increment has the same precedence as pointer dereference, but associates right-to-left. Therefore, ++ *(dblptr) is the same as ++ (*(dblptr)).

Side note: you understand, of course, that incrementing a pointer that does not point into an array is allowed under the standard, but dereferencing it leads to UB (undefined behavior).