Putting ++
after the a
tells it to return the old value, then increment. At the same time, the incrementing happens before the assignment, so you lose the old value. Here is equivalent code:
int a = 1;
int temp_old_a = a; //temp_old_a is 1
a = temp_old_a + 1; //increments a to 2, this assignment is from the ++
a = temp_old_a; //assigns the old 1 value thus overwriting, this is from your line's assignment `a =` operator
Console.Write(a); //1
So you can see how it ultimately, throws away the incremented value. If on the other hand you put the ++
before the a
:
int a = 1;
a = ++a;
Console.Write(a); //2
It acts like:
int a = 1;
int temp_old_a = a;
temp_old_a = temp_old_a + 1;
a = temp_old_a; //assigns the incremented value from the ++
a = temp_old_a; //assigns again as per your original line's assignment operator `a =`
Console.Write(a); //2
In this case, it usually doesn't make sense to reassign a variable when having it incremented as part of the expression. You're almost always better off just simply incrementing it:
int a = 1;
a++; //or ++a, but I find a++ is more typical
Console.Write(a); //2
It's usually more standard to see code like that and far less confusing (as you've found out).