Reputation: 1315
Here is the code I'm running:
#include <iostream>
using namespace std;
int main()
{
int x = 5;
int *p;
p = &x;
*p++;
cout<<x<<endl;
return 0;
}
The output should be 6, because p
is pointing at the address of x
. However, I get 5.
But more interestingly, I couldn't understand why the output is 6 when I change *p++
with *p = *p+1
. Why is this?
Upvotes: 1
Views: 127
Reputation: 123458
Postfix ++
has higher precedence than unary *
, so *p++
is parsed as *(p++)
; IOW, you're incrementing the pointer, not the thing being pointed to.
Use (*p)++
to increment the thing being pointed to, or use ++*p
.
Upvotes: 3
Reputation: 275385
Use brackets if you do not understand operator precedence.
*p++
is
*(p++)
and you want
(*p)++
The rule of thumb is:
Upvotes: 0
Reputation: 52538
You are wrong. *p++ reads the value that p points to, then increases the pointer p. You probably wanted (*p)++.
*p = *p + 1 works because it is correct.
Upvotes: 7