Prefix vs Postfix increment in C++
It doesn’t matter much, but you should use ++i
instead of i++
in C++.
First let’s look at how ++i
and i++
differ:
// How pre-increment works. Increment, _then_ return i.
#include <iostream>
int main() {
int i = 0;
std::cout << ++i; // prints 1.
}
// How post-increment works. Return i, _then_ increment.
#include <iostream>
int main() {
int i = 0;
std::cout << i++; // prints 0.
}
Let’s try using it in a for loop:
#include <iostream>
int main() {
auto it = GetMyIterator();
// Pre-increment increments the iterator and returns a _reference_ to it.
for (; !it->end(); ++it) {
// ...
}
}
But what happens when we use post-increment in a for loop?
#include <iostream>
int main() {
auto it = GetMyIterator();
// it++ is supposed to return `it`, but it no longer exists because you incremented it.
// So that means it's actually returning a copy. You'll find that when you
// try to implement the post-increment iterator, you have to do a copy!
for (; !it->end(); it++) {
// ...
}
}
As illustrated above: if i
is not an int
but an iterator, post-increment ends up returning
an unneeded copy of the iterator’s first value. Compilers are generally smart enough to optimize
this away, but in the rare case that they don’t / can’t, it’s wise to use pre-increment.