What's the difference between X = X++; vs X++;?
X++ will increment the value, but then return its old value.
So in this case:
static void Main(string[] args)
{
int x = 10;
x = x++;
Console.WriteLine(x);
}
You have X at 11 just for a moment, then it gets back to 10 because 10 is the return value of (x++).
You could instead do this for the same result:
static int plusplus(ref int x)
{
int xOld = x;
x++;
return xOld;
}
static void Main(string[] args)
{
int x = 10;
x = plusplus(x);
Console.WriteLine(x);
}
It is also worth mentioning that you would have your expected result of 11 if you would have done:
static void Main(string[] args)
{
int x = 10;
x = ++x;
Console.WriteLine(x);
}
In the assignment x = x++
you first extract the old value of x
to use in evaluating the right-hand side expression, in this case 'x'; then, you increment x
by 1. Last, you assign the results of the expression evaluation (10) to x
via the assignment statement.
Perhaps an equivalent code would make the predicament clear:
var tmp = x;
x++;
x = tmp;
This is the equivalent of your x = x++
code in C#.
The behaviour of x++ is to increment x but return the value before the increment. Its called a post increment for this reason.
So x = x++; simply put will
1. return the value, then
2. increment x, then
3. assign the original value(returned in step 1) of x to x.
x = 10
x = ++x
x
would end up equalling 11.
x++;
does the following:
int returnValue = x;
x = x+1;
return returnValue;
As you can see, the original value is saved, x is incremented, and then the original value is returned.
What this ends up doing is saving the value 10 somewhere, setting x equal to 11, and then returning 10, which causes x to be set back to 10. Note that x does actually become 11 for a few cycles (assuming no compiler optimization).