I've got a code here, using a pointer and dereferencing to change the element value in an array.
int arr[] = {6, 7, 8, 9, 10};
int *ptr = arr;
*ptr++ = *ptr++ + 123;
*(++ptr) = *(++ptr) + 123;
int *p = arr;
int *q = arr + sizeof(arr)/sizeof(*arr);
while( p != q )
cout << *p++ << " "; // 129 7 8 9 133
First of all, it is a really bad style, since one subexpression changes the value of operand on the other subexpression.
My question is, how does underlying operation of this expression go
*ptr++ = *ptr++ + 123;
In my imagination, the first increment may effect the increment on right-hand side or the second one effect the first one.
so may the result go with 130 and change the value on the location of 6,
or
may the result go with 129 and change the value on the location of 7...
But the result is not what I expect ( it goes change the value on location of 6 and the pointer goes to the location of 8)
I can not figure out what the underlying operations are.
e.g.
- increment left-hand side, keep the location of 6, and pointer increments
- increment the operand on right-hand side, keep the location of 7, and pointer increments
- do the additional operator. It is 7 + 123
- do the assignment operator. The value of location 6 changed to 130
What's wrong? How should I break this apart? Thanks!