Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

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

I'm well aware that in C++

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

has different effect compared to

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

but every once in a while I see statements with prefix increment in for-loops or just by their own:

for( int i = 0; i < count; ++i ) {
     //do stuff
}

or

for( int i = 0; i < count; ) {
    //do some stuff;
    if( condition ) {
        ++i;
    } else {
        i += 4;
    }
}

In the latter two cases the ++i looks like an attempt to produce smarty-looking code. Am I overseeing something? Is there a reason to use ++i instead of i++ in the latter two cases?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...