C # compiler question?
Hello everyone, in the following code, what should be the result of d after the second expression?
int d = 1;
d += d++;
D was supposed to be 3 after, but the unary increment d ++ doesn't seem to take effect and d will keep the value 2.
Is there a name for this error? Does it exist for other compilers that support unary increment like C #?
source to share
If you look at the generated IL, you can see why the result is 2 and not 3.
IL_0000: ldc.i4.1 // load constant 1 on evaluation stack
IL_0001: stloc.0 // pop and store value in local 0
IL_0002: ldloc.0 // load value of local 0 on evaluation stack
IL_0003: ldloc.0 // repeat, stack is now 1, 1
IL_0004: dup // duplicate topmost value on evaluation stack,
// i.e. stack is now 1, 1, 1
IL_0005: ldc.i4.1 // load constant 1 on evaluation stack
IL_0006: add // add two topmost values on stack,
// i.e. 1 and 1 and push result on stack
IL_0007: stloc.0 // pop and store this value in local 0
IL_0008: add // add the two remaining values on the stack
// which again happens to be 1 and 1 and push result to stack
IL_0009: stloc.0 // pop and store this value in local 0
In other words: The memorized final value is the sum of 1 and 1.
(the above code is from a release mode build)
source to share
If you rewrite your code this way, it will set d to be 3:
int d = 1; d += ++d;
Look at the ++ Operator documentation for an explanation of why your example behaves the way it does.
Excerpts:
The second form is a postfix increment operation. The result of the operation is that the value of the operand before it has been incremented.
As @Guffa pointed out, this is not a bug, just that the result of your postfix increment operation is d
overwritten by the operation +=
.
source to share
I often have questions about ++ operators being "broken"; this is almost always because the person asking the question is being used the way he or she works in some language where the ++ behavior is undefined, such as C ++. Here's a recent article I wrote about such a scenario:
http://blogs.msdn.com/ericlippert/archive/2009/08/10/precedence-vs-order-redux.aspx
source to share
... and this will be an example of why I find the post / pre-increment / decment statements to be very unreadable when used in an expression with other statements. The behavior you are describing is correct, but it is difficult to reason, which leads to misunderstandings and errors.
Despite the fact that this is a phrase, I would rewrite it as:
int d = 1; d += d; ++d;
Note the use of the pre-increment operator instead of post-increment so that the compiler doesn't think it needs to keep a copy of the old value.
source to share