A place to breathe

Thursday, December 4, 2008

C++: Pre-increment v. Post-increment

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:

class Obj

{

// pre-inc

// “increment this var and give me the incremented var”

Obj & operator++ ()

{

++blah;

return *this;

}



Private:

type blah;

}



//postincrement. Operator overloading:

class Obj

{

// post-increment

// “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

}



Private:

type blah;

}


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.

No comments:

About Me

I'm currently a software engineer. My specific interest is games and networking. I'm running software company called Nusantara Software.