doc-helmut wrote:the prefix ++i version usually uses temporary variables to store the old index in case the old value (i) is needed while i already has been incremented to (i+1).
You got that the wrong way round....
Think of the ++i and i++ operators as functions like this
Code: Select all
int increment_before(int& i) // ++i
{
i = i+1;
return i;
}
// and
int increment_after(int& i) // i++
{
int temp= i; // remember old value
i = i+1;
return temp;
}
If you use i++/++i inside loops, i coud be an Iterator in C++:
Code: Select all
std::vector<int> integerVector;
// Fill vec with values
std::vector<int>::iterator i = integerVector. begin();
for ( ; i != integerVector. end(); ++i)
{
// Do something with current value
cout << (*i) << endl;
}
The choice for "++i" had a reason in this case. If you don't need the return value of an expression like this (such as in for-loops), use the ++i version.
While this doesn't matter with integers, it might matter with iterators or objects (if you overloaded ++). Looking at example-functions:
Code: Select all
MyClass increment_before(MyClass& k) // ++k
{
// increment k here
return k;
}
// and
MyClass increment_after(MyClass& k) // k++
{
MyClass temp = MyClass(k); // remember old value
// increase k here
return temp;
}
As we're using objects here, in the 2nd case an object clone has to be created.
That is why there is a simple beauty of this rule:
If you just want to increment something (and you don't need the expression), always use ++i. It's always at least as fast as i++, but in C++ for special cases with iterators or objects, ++i is faster.
Always prefer ++i for increments in C and C++, and you never go wrong. Simple
On the other hand, we are talking about C and NXC, not C++
Yes, but if there is a rule which doesn't matter in the worst case but helps in the best case and applies for C and C++, you might as well remember it.
I doubt that ANSI C prefix ++i is faster than postfix i++
The standard only specifies how the language has to work. Whether the compiler optimizes away the temp-variable or not is a choice of implementation. So it indeed depends on the compiler and optimization-level!
which is simply the fastest i=i+1 without any temp variable not even using the RAM for calculation (in C it's a direct register operation).
Wrong, as we've seen above. The temp-variable is indeed needed with i++ and not with ++i. Whether the compiler makes the actual increment-step a register operation, and if it optimizes away the temp-variable when it's not needed, is compiler-specific.
So please CMIIW, but honestly, I'm not sure if your post helps a lot along, Linus
You may decide that for yourself, but 1) now you know your understanding of ++i vs i++ was wrong, and 2) now everybody can safely trust the "in general, ++i is equal or faster than i++ for incrementations only, always" rule.