Pre- & Post Increment in C#

前端 未结 6 730
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  -上瘾入骨i
    2020-11-27 06:13

    x-- will be 4, but will be 3 at the moment of --x, so it will end being 2, then you'll have

    x = 4 - 2
    

    btw, your first case will be x = 4 + 6

    Here is a small example that will print out the values for each part, maybe this way you'll understand it better:

    static void Main(string[] args)
    {
        int x = 4;
        Console.WriteLine("x++: {0}", x++); //after this statement x = 5
        Console.WriteLine("++x: {0}", ++x); 
    
        int y = 4;
        Console.WriteLine("y--: {0}", y--); //after this statement y = 3
        Console.WriteLine("--y: {0}", --y);
    
        Console.ReadKey();
    }
    

    this prints out

    x++: 4
    ++x: 6
    y--: 4
    --y: 2
    

提交回复
热议问题