Let's put some context to that (excuse my variable names; I was typing this up quickly):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
#include <iostream>
using std::cout;
int main()
{
int a[] = {1,2,3,4,5,6,7};
int* p = a, *q = a+3;
cout << "The array before:\n";
for (int i : a)
cout << i << ' ';
cout << "\nPosition of p before: " << (p-a);
cout << "\nPosition of q before: " << (q-a);
*p++ = *q++;
cout << "\n\nArray after:\n";
for (int i : a)
cout << i << ' ';
cout << "\nPosition of p after: " << (p-a);
cout << "\nPosition of q after: " << (q-a);
}
|
The array before:
1 2 3 4 5 6 7
Position of p before: 0
Position of q before: 3
Array after:
4 2 3 4 5 6 7
Position of p after: 1
Position of q after: 4 |
Now,
*p++ = *q++;
is the same as
*(p++) = *(q++)
, since
++ has a higher precedence than
* (which means the
++ happens before the
*).
Before this,
p is pointing at the first element of
a and
q is pointing at the 4
th element of
a.
Now,
q++
means "increment the position of
q and give me back the old value", so
*q++
increments
q and gives you the value in the array at the old position.
Basically, it's the same as doing
*q
followed by
q++;
later on.
So
*q++
returns the element in the fourth position of
a (which is 4) and then increments
q (so now
q is pointing at the fifth element of
a).
The same thing happens with
*p++
-- it increments
p (to make it point at the 2nd position of
a now) and then gives you the array element at the old position of p (which is 1). In this case, it's setting that element equal to the right-hand side of that expression, which we just figured out above to be 4.
So basically, all you really have to get out of it is this:
1)
*p++ = *q++
is the same as
2) Use parenthesis to avoid confusion. In this case, it would have been much clearer if it had been written as
*(p++) = *(q++)
rather than
*p++ = *q++
.
2) Sometimes clarity is better than brevity. Write code that you can actually understand (and will be able to understand when you look back at it 6 months afterwards).
(Hopefully, that goes without saying anyways, but....)