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

后端 未结 22 1767
暗喜
暗喜 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:34

    a++ is known as postfix.

    add 1 to a, returns the old value.

    ++a is known as prefix.

    add 1 to a, returns the new value.

    C#:

    string[] items = {"a","b","c","d"};
    int i = 0;
    foreach (string item in items)
    {
        Console.WriteLine(++i);
    }
    Console.WriteLine("");
    
    i = 0;
    foreach (string item in items)
    {
        Console.WriteLine(i++);
    }
    

    Output:

    1
    2
    3
    4
    
    0
    1
    2
    3
    

    foreach and while loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:

    for (int i = 0; i < 5; i++) { Console.Write(i);}
    Console.WriteLine("");
    for (int i = 0; i < 5; ++i) { Console.Write(i); }
    

    0 1 2 3 4
    0 1 2 3 4

    If the value as evaluated is used then the type of increment becomes significant:

    int n = 0;
    for (int i = 0; n < 5; n = i++) { }
    

提交回复
热议问题