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

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

    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;
    }
    

提交回复
热议问题