Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre/Post Increment Pointers in C++

*(p1++)

int array[10] = {1,2};
int *p1 = array;
*p1=24;
*p1= *(p1++);
for (int i : array)
    cout << i << " ";

Output is 24 24

*(++p1)

int array[10] = {1,2};
int *p1 = array;
*p1=24;
*p1= *(++p1);
for (int i : array)
    cout << i << " ";

Output is 24 2

It seems like this is the exact opposite of doing increment with values. Can someone explain what is going on here? Thanks!

like image 884
Patrick Duncan Avatar asked May 26 '26 10:05

Patrick Duncan


2 Answers

There is an undefined behavior in

*p1 = *(p1++);

because, quoting §1.9/15:

If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

Side effect here is an increment of p1 and value computation is a computation of address using p1.

So you shouldn't rely on the exact outcome of your examples.

like image 61
vitaut Avatar answered May 30 '26 03:05

vitaut


*p1= *(p1++);

This just doesn't make sense. The semantic meaning of this operation is different depending on which side of the = is evaluated first. So there's no way you can make any sense out of it.

like image 31
David Schwartz Avatar answered May 30 '26 04:05

David Schwartz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!