-1

As a beginner, I had difficulty understanding the code below. I expected the a increments twice and the result will be 2 but it isn't.

var a = 0;
a += ++a;
Console.WriteLine(a); // 1

It seems like one value is dropped. How to understand that?

  • See also very closely related https://stackoverflow.com/questions/33783989/post-increment-within-a-self-assignment. More generally, you should read the language reference when you're unsure about things like this. The documentation spells out clearly the exact order of evaluation and operator precedence. – Peter Duniho Mar 16 '20 at 05:24

1 Answers1

1

Well, a += n is equivalent to a = a + n

a += ++a; is therefore equivalent to a = a + ++a;

In turn, this is equivalent to a = a + (a + 1);

Substituting your value of a, we get a = 0 + (0 + 1);

Remember that operands in an expression are evaluated from left to right. Eric Lippert goes into evaluation order in depth here.

What does this mean in practice?

Well, if we write a = a + ++a;, a will become 1 because the first a is 0 at the time of evaluation, and then becomes 1 in ++a, meaning the overall assignment is a value of 1.

If we reverse this a little and instead write a = ++a + a; then ++a will calculate 1, and by the time we reach the second a, it's already 1, meaning that we effectively have a = 1 + 1; so we get 2.

You can verify that with the following code:

var a = 0;
a = a + ++a;
var b = 0;
b = ++b + b;
Console.WriteLine(a); // 1
Console.WriteLine(b); // 2

Try it online

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86