Why use ++i instead of i++ in cases where the value is not used anywhere else in the statement?

前端 未结 7 1744
情深已故
情深已故 2020-12-02 20:52

I\'m well aware that in C++

int someValue = i++;
array[i++] = otherValue;

has different effect compared to

int someValue =          


        
7条回答
  •  甜味超标
    2020-12-02 21:32

    Look at possible implementations of the two operators in own code:

    // Pre-increment
    T*& operator ++() {
        // Perform increment operation.
        return *this;
    }
    
    // Post-increment
    T operator ++(int) {
        T copy = *this;
        ++*this;
        return copy;
    }
    

    The postfix operator invokes the prefix operator to perform its own operation: by design and in principle the prefix version will always be faster than the postfix version, although the compiler can optimize this in many cases (and especially for builtin types).

    The preference for the prefix operator is therefore natural; it’s the other that needs explanation: why are so many people intrigued by the use of the prefix operator in situations where it doesn’t matter – yet nobody is ever astonished by the use of the postfix operator.

提交回复
热议问题