C# Pre- & Post Increment confusions-Collection of common programming errors
Lets have a look at the IL that gets generated from that statement
IL_0002: ldloc.0
Loads the value of x onto the stack. Stack => (4)
IL_0003: dup
Duplicates the topmost item on the stack. Stack => (4, 4)
IL_0004: ldc.i4.1
Push 1 onto the stack. Stack => (1, 4, 4)
IL_0005: sub
Subtract the two top values and push result onto the stack. Stack => (3, 4)
IL_0006: stloc.0
Store the topmost value of the stack back to x. Stack => (4)
IL_0007: ldloc.0
Load the value of x back into the stack. Stack => (3, 4)
IL_0008: ldc.i4.1
Load the value 1 onto the stack. Stack => (1, 3, 4)
IL_0009: sub
Subtract the two. Stack => (2, 4)
IL_000A: dup
Duplicate the top value => (2, 2, 4)
IL_000B: stloc.0
Store the top value back to x. Stack => (2, 4)
IL_000C: sub
Subtract the two top values. Stack => (2)
IL_000D: stloc.0
Store this value back into x. x == 2
Originally posted 2013-11-09 23:23:06.