Search code examples
c#compiler-constructionincrementunary-operator

C# Compiler Behavior Question?


Hey everyone, in the following code, what should the result of d be after the second expression?

        int d = 1;
        d += d++;

One would assume d is 3 afterwards but the unary increment d++ doesn't seem to take effect and d retains a value of 2.

Is there a name for this bug? Does it exist for other compilers that support unary increment like C#?


Solution

  • If you take a look at the generated IL, you'll 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 final value stored is the sum of 1 and 1.

    (the code above is from release mode build)