Pre- & Post Increment in C#

前端 未结 6 743
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 05:46

I am a little confused about how the C# compiler handles pre- and post increments and decrements.

When I code the following:

int x = 4;
x = x++ + ++x         


        
6条回答
  •  囚心锁ツ
    2020-11-27 06:01

    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

提交回复
热议问题