I understand the differences between i++ and ++i, but I\'m not quite sure why I\'m getting the results below:
static void Main(string[] args)
{
int c = 4
According to the MSDN page on C# operators the assignment operator (=
) has lower precedence than any primary operator, such as ++x
or x++
.
That means that in the line
c = c++;
the right hand side is evaluated first. The expression c++
increments c
to 43, then returns the original value 42
as a result, which is used for the assignment.
As the documentation you linked to states,
[The second form is a] postfix increment operation. The result of the operation is the value of the operand before it has been incremented.
In other words, your code is equivalent to
// Evaluate the right hand side:
int incrementResult = c; // Store the original value, int incrementResult = 42
c = c + 1; // Increment c, i.e. c = 43
// Perform the assignment:
c = incrementResult; // Assign c to the "result of the operation", i.e. c = 42
Compare this to the prefix form
c = ++c;
which would evaluate as
// Evaluate the right hand side:
c = c + 1; // Increment c, i.e. c = 43
int incrementResult = c; // Store the new value, i.e. int incrementResult = 43
// Perform the assignment:
c = incrementResult; // Assign c to the "result of the operation", i.e. c = 43