Difference between i++ and ++i in a loop?

2018-12-31 04:08发布

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

21条回答
步步皆殇っ
2楼-- · 2018-12-31 04:36

There can be a difference for loops. This is the practical application of post/pre-increment.

        int i = 0;
        while(i++ <= 10) {
            Console.Write(i);
        }
        Console.Write(System.Environment.NewLine);

        i = 0;
        while(++i <= 10) {
            Console.Write(i);
        }
        Console.ReadLine();

While the first one counts to 11 and loops 11 times, the second does not.

Mostly this is rather used in a simple while(x-- > 0 ) ; - - Loop to iterate for example all elements of an array (exempting foreach-constructs here).

查看更多
人间绝色
3楼-- · 2018-12-31 04:41

Since you ask about the difference in a loop, i guess you mean

for(int i=0; i<10; i++) 
    ...;

In that case, you have no difference in most languages: The loop behaves the same regardless of whether you write i++ and ++i. In C++, you can write your own versions of the ++ operators, and you can define separate meanings for them, if the i is of a user defined type (your own class, for example).

The reason why it doesn't matter above is because you don't use the value of i++. Another thing is when you do

for(int i=0, a = 0; i<10; a = i++) 
    ...;

Now, there is a difference, because as others point out, i++ means increment, but evaluate to the previous value, but ++i means increment, but evaluate to i (thus it would evaluate to the new value). In the above case, a is assigned the previous value of i, while i is incremented.

查看更多
听够珍惜
4楼-- · 2018-12-31 04:41

There is more to ++i and i++ than loops and performance differences. ++i returns a l-value and i++ returns an r-value. Based on this, there are many things you can do to ( ++i ) but not to ( i++ ).

1- It is illegal to take the address of post increment result. Compiler won't even allow you.
2- Only constant references to post increment can exist, i.e., of the form const T&.
3- You cannot apply another post increment or decrement to the result of i++, i.e., there is no such thing as I++++. This would be parsed as ( i ++ ) ++ which is illegal.
4- When overloading pre-/post-increment and decrement operators, programmers are encouraged to define post- increment/decrement operators like:

T& operator ++ ( )
{
   // logical increment
   return *this;
}

const T operator ++ ( int )
{
    T temp( *this );
    ++*this;
    return temp;
}
查看更多
登录 后发表回答