Post-increment within a self-assignment

前端 未结 6 1541
南方客
南方客 2020-12-02 22:30

I understand the differences between i++ and ++i, but I\'m not quite sure why I\'m getting the results below:

static void Main(string[] args)
{
    int c = 4         


        
6条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 23:27

    The docs say for postfix state:

    The result of the operation is the value of the operand before it has been incremented.

    This means that when you do:

    c = c++;
    

    You're actually re-assigning 42 to c, and that's why you're seeing the console print 42. But if you do:

    static void Main(string[] args)
    {
        int c = 42;
        c++;
        Console.WriteLine(c);  
    }
    

    You'll see it output 43.

    If you look at what the compiler generates (in Debug mode), you'll see:

    private static void Main(string[] args)
    {
        int num = 42;
        int num2 = num;
        num = num2 + 1;
        num = num2;
        Console.WriteLine(num);
    }
    

    Which shows the overwrite more clearly. If you look at Release mode, you'll see the compiler optimize the entire call to:

    private static void Main(string[] args)
    {
        Console.WriteLine(42);
    }
    

提交回复
热议问题