Point: Favor Pre-increment over post-increment whenever possible.
In C++, pre-increment means “increment this var and give me that incremented var”, whereas post-increment means “give me the var value, and increment the var”. We agree that they behave differently, but somewhat similar (increment the value of a var).
We don’t want to get confused when we use it in this kind of code:
int ch = arr[ i++ ]
int ch = arr[ ++i ]
Both will give different results and therefore, are not similar (why?).
However this doesn’t mean that we have to use pre-increment all the time.
But why we care?
Basically, the idea would be we can save some instructions generated by the compiler by using pre-increment operation.
Pre-increment and post-increment don’t matter much for built-in types like “int”. Most likely, the compiler knows how to optimize it away anyway.
However, it may have some performance impact when we increment an instance of a class that defines the operator “++”. In C++, we call this “operator overloading”. Operator overloading of “++” are being used extensively in STL (standard template library). If you're using STL extensively, you should get the habit of doing pre-increment.
The following shows how it differs:
// preincr. Operator overloading:
// “increment this var and give me the incremented var”
Obj & operator++ ()
//postincrement. Operator overloading:
// “give me the var value, and increment this var”
Obj & operator++ ()
Obj copy (*this) // copy this object
++(*this) ; // call pre-increment operator
return copy; // return the original value being copied
You can see that above that eventually, post-increment operator would call the pre-increment operator anyway. So there are some extra steps being done here for post-increment. When we compile, this translates into even more instructions need to be executed.
Almost always, you just want to increment the variable and pre-increment does no harm.
A place to breathe
- ► 2014 (22)
- ▼ December (7)