-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 
6
  • 6
    So what's the question here? You answered and proved your own question... Commented May 18, 2018 at 14:08
  • Order of Operations. And what might happen if you switch to sum += ++sum Commented May 18, 2018 at 14:09
  • 2
    I think the question is how; sum += sum++; is different from sum += sum + 1; Commented May 18, 2018 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. Commented May 18, 2018 at 14:14
  • 1
    What about sum += ++sum; Commented May 18, 2018 at 14:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.