Patrick Wood said:
I found a problem with C# and post increments. I was going
through some source code in c++ and found someone did a
post increment:
int x=0;
for(int i=0; i<10; i++)
{
x = x++;
}
In c++, you'd get 0,1,...,9 (as expected). This doesn't
work in C#. In C#, you get 0,...,0. It seems the post
increment is ignored in this case. However, the lines:
x=4;
y=x++;
produces y=4, x=5 (as expected)
Should c# be behaving this way or is there a compiler
error? After looking at the assembly code in c++ and c#, it
looks like a bug in c#.
I'll retract my previous thoughts on this because the specs appear to
describe this behavior as correct:
14.5.9 Postfix increment and decrement operators
.. If x is classified as a variable:
x is evaluated to produce the variable.
The value of x is saved.
The selected operator is invoked with the saved value of x as its argument.
The value returned by the operator is stored in the location given by the
evaluation of x.
The saved value of x becomes the result of the operation.
Here's my interpretation of what this says:
using System;
class PostIncrementTest
{
static void Main()
{
int x = 0;
// * x is evaluated to produce the variable.
// * The value of x is saved.
int savedX = x;
// * The selected operator is invoked with
// the saved value of x as its argument.
// * The value returned by the operator
// is stored in the location given by the
// evaluation of x.
x = savedX + 1;
// * The saved value of x becomes the result
// of the operation.
x = savedX;
Console.WriteLine("x = {0}", x);
//
// However, when y is used you get this
//
x = 0;
int y = 0;
// * x is evaluated to produce the variable.
// * The value of x is saved.
savedX = x;
// * The selected operator is invoked with
// the saved value of x as its argument.
// * The value returned by the operator
// is stored in the location given by the
// evaluation of x.
y = savedX + 1;
// * The saved value of x becomes the result
// of the operation.
x = savedX;
Console.WriteLine("x = {0}, y = {1}", x, y);
Console.ReadLine();
}
}
And the output:
x = 0
x = 0, y = 1
To be sure, I'd be interested in seeing if someone from MS could clarify.
Joe