for-looplanguage-agnosticpost-incrementpre-increment

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


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


Solution

  • 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++) { }