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?
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?
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