Difference between pre-increment and post-increment in a loop?

后端 未结 22 1769
暗喜
暗喜 2020-11-21 23:41

Is there a difference in ++i and i++ in a for loop? Is it simply a syntax thing?

22条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 00:36

    In C# there is no difference when used in a for loop.

    for (int i = 0; i < 10; i++) { Console.WriteLine(i); }
    

    outputs the same thing as

    for (int i = 0; i < 10; ++i) { Console.WriteLine(i); }
    

    As others have pointed out, when used in general i++ and ++i have a subtle yet significant difference:

    int i = 0;
    Console.WriteLine(i++);   // Prints 0
    int j = 0;
    Console.WriteLine(++j);   // Prints 1
    

    i++ reads the value of i then increments it.

    ++i increments the value of i then reads it.

提交回复
热议问题