Patrick Duncan
Patrick Duncan

Reputation: 559

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!

Upvotes: 3

Views: 668

Answers (3)

Iinferno1
Iinferno1

Reputation: 49

For *(p1++):

*p1 = *(p1++)

p1++ will increment p1 to point to index 1 in the array, and return the previous value of p1 (index 0). So *(p1++) will return 24, and *p1 will now equal 2. *p1 is then assigned that return value (24), so the array will be {24,24}.

for *(++p1):

*p1 = *(++p1)

++p1 will increment p1 to point to index 2 in the array, and return the current value of p1 (index 1). So *(++p1) will return 2, and *p1 will now equal 2. *p1 is then assigned that return value (2), which is the original value at the index of p1 (1), so the array will remain {24,2}

Upvotes: -1

vitaut
vitaut

Reputation: 55524

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.

Upvotes: 2

David Schwartz
David Schwartz

Reputation: 182743

*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.

Upvotes: 1

Related Questions