-4

I have this code snippet below. Is it correct to describe that sum will be 0 because sum++ will be ignored as assignment of sum += will be adding 0 before increasing the value? Or how is this best described? I mean if I use sum += sum + 1 the result is different.

int sum = 0;
for (int i = 0; i < 10; i++)
{
   sum += sum++;
}

// Sum has end value 0
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
serializer
  • 1,003
  • 2
  • 13
  • 27
  • 6
    So what's the question here? You answered and proved your own question... – Isma May 18 '18 at 14:08
  • Order of Operations. And what might happen if you switch to sum += ++sum – Ryan Wilson May 18 '18 at 14:09
  • Possible duplicate of [When does postincrement i++ get executed?](https://stackoverflow.com/questions/5433852/when-does-postincrement-i-get-executed) – Mattias Backman May 18 '18 at 14:11
  • 2
    I think the question is how; sum += sum++; is different from sum += sum + 1; – serializer May 18 '18 at 14:13
  • 1
    I think you are correct, yes. Essentially it loads `sum` into memory position 1 . Then it loads sum again into memory position 2. It then adds one to memory position 2 and stores the result to `sum` (without updating memory position 2). It then adds up memory positions 1 and 2 (both still 0) and assigns the result of that to sum so sum is 0 again. – Chris May 18 '18 at 14:14
  • 1
    What about `sum += ++sum;` – Patrick Hofman May 18 '18 at 14:20

1 Answers1

1

sum++ increments the value, but it returns the value it was before it was incremented. ++sum increments the value as well, but returns the value after the incrementing.

You can think sum++ as returning the value, then increasing the value (even though that's not what's happening)

And you think ++sum as increasing the value and then returning it.

So, sum += ++sum is the same as sum += sum + 1, as far as final result goes.

In your example, sum++ returns zero, sum is set two 1, but then you set it back to 0 and it repeats.

AustinWBryan
  • 3,249
  • 3
  • 24
  • 42