-3

As I already know, the operator ++ has a difference between two situations: x++, and ++x; Though, When I try to write such a code:

int x = 5;
int* y = &x;
int value;
value = *y++ + ++*y;

the value of value, is 12, in the end of the equation. If I swap the equation to be

value = ++*y + *y++;

It is also 12, and I don't understand the rule. What is he doing first? In two cases the y pointer points to garbage.

Thanks, Uriah.

Uriah Ahrak
  • 31
  • 1
  • 4
  • 4
    Well, there is undefined behavior in your code. See this --> http://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior – Haris Jan 26 '16 at 08:53
  • 2
    Don't write such code, it's both cryptic and leads to undefined behavior. What are you trying to achieve? – August Karlstrom Jan 26 '16 at 08:55
  • 2
    look this post there is an overview http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – terence hill Jan 26 '16 at 08:57

1 Answers1

1

This line leads to undefined behaviour:value = *y++ + ++*y;
*y++ is equivalent to *(y++), so it increments the pointer, not the actual value.
After that, ++*y dereferences y which causes undefined behaviour.

In the second example, ++*y actually increments the value where y points to.
So x will be 6. After that *y++ dereferences y which will also give 6.
So thats why 12 is calculated in the second example.
Dereferencing y after also causes undefined behaviour, so its best to avoid code like this.

Viktor Simkó
  • 2,607
  • 16
  • 22