0

Why can I do something like *x = *x+1;, but doing something like *x = *x++; doesn't seem to have any affect?

Code:

// Example program
#include <iostream>
#include <string>

using namespace std;

void doSomething(int *x, int *y)
{
    *x = *x++;
    *y = *y + 5;
}

int main()
{
    int x = 4;
    int y = 3;
    doSomething(&x, &y);
    cout << "x is now: " << x << endl; //outputs 4
    cout << "y is now: " << y << endl; //outputs 8
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
simon
  • 854
  • 1
  • 9
  • 23

3 Answers3

2

This statement

*x = *x+1;

can be written like

*x = ++*x;

Of course you could just write

++*x;

As for this statement

*x = *x++;

then it is equivalent to

*x = *( x++ );

and has undefined behavior because the side effect of the post-increment operator is not sequenced.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

The postfix operator ++ has a higher precedence from the dereference * operator. The statement *x = *x++; is executed as follows *x = (*(x++))

As you can see the ++ operator is executed first making the pointer point to where it was pointing. From there, the dereference operator is executed. If you want to increment the actual value of x just write ++*x;

KostasRim
  • 2,053
  • 1
  • 16
  • 32
-1

Because all expressions follow operators precedence rule.

As you can see in the table the operator operator++ has higher precedence than operator*

You can better follow with parenthesis, the code:

*x = *x++;

is equivalent to:

*x = *(x++);

In short, you're incrementing the value of the pointer and after you dereference it.

In memory it happens something like:

|  x = 4   |     <---- &x
|  trash   |
|  trash   |

You increment the pointer which will points the next cell in the memory:

|  x = 4   |     
|  trash   |     <---- &x+1
|  trash   |

And with assign its value to itself, anyway it's trash.


Solution

In order to avoid miss-understanding the usage of parenthesis should be a valid help.

Fix it with:

*x = ++(*x);
BiagioF
  • 9,368
  • 2
  • 26
  • 50
  • `*x = (*x)++;` and now you have *another* problem. What about just `(*x)++;`? – Bo Persson Aug 29 '16 at 16:44
  • @BoPersson Sorry too fast, I fixed – BiagioF Aug 29 '16 at 16:49
  • _"you're incrementing the value of the pointer and after you dereference it"_. Is that true? The increment is a side effect that could happen before or after the assignment. My understanding is that `*x++` will always dereference `x`'s original position, then later `x` will move to point to the next position. So the result is undefined? Maybe the trash location gets the value of 4 assigned? – wally Aug 29 '16 at 17:23