Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#?

like image 256
t3rse Avatar asked May 20 '26 14:05

t3rse


2 Answers

It's not a bug, it acts exactly as expected.

The += operator expands into this:

d = d + d++;

That means that the change that the ++ operator causes is overwritten when the result is assigned back to the variable.

like image 70
Guffa Avatar answered May 23 '26 03:05

Guffa


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)

like image 34
Brian Rasmussen Avatar answered May 23 '26 04:05

Brian Rasmussen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!