Harold Serrano

View Original

Prefer pre-increment to post-increment

What is wrong with the following statement?

x=y++;

Nothing really. The only problem is that the increment function has to make a copy of the original value of y, increment y and then return the original value. So when you do a post-increment you are involving the construction of a temporary object. Whereas, pre-increment does not.

If you are using integers, there is no additional overhead, however for user-defined types, there is and is wasteful. Thus, whenever you have the option, use pre-increment instead of using post-increment.