#### Archived

This topic is now archived and is closed to further replies.

# Prefix vs postfix

This topic is 6934 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I think I may have posted this before... I can''t remember, so even if I did, I still need the answer Which of the following will run faster? for (int i = 0; i < 10; i++) cout << i << endl; for (int i = 0; i < 10; ++i) cout << i << endl; See the difference? i++ or ++i? According to the c++ book I have, postfix has about 5x the code in it as prefix, does that make a difference? --------------------

You are not a real programmer until you end all your sentences with semicolons;

Visit the ROAD Programming Website for more programming help.

##### Share on other sites
Prefix should run faster than postfix.

The reason is that the postfix increment operator creates a temporary object that will hold the original value that will be returned. The prefix operator++ will increase the value and return the object itself.

Erik

##### Share on other sites
In this particular case, there is probably no difference. A decent compiler will most likely see that you are not using the value returned by ++i or i++ and will convert either one into a single assembly language increment instruction.

##### Share on other sites
Yep, it should make no difference in this case, but I decided it would be a good idea to get into the habit of using prefix all the time unless I needed postfix. This saves the compiler even having to think about optimising, and also helps if you''re incrementing something more complex than a basic type (eg. STL iterator) where the compiler may not be able to optimise it down to the same instructions.

##### Share on other sites
There is totally a difference between them!!! Whether the ++ is before or after the variable determine WHEN it is increment, before (prefix) or after (postfix) evaluation!
Lets say you have this:
int x = 0;while(true)   if(x++==1) {DoStuff();}

In this case, it would take two loops for x to equal 1, since x is evaluated and THEN it is incremented. In this case:
int x = 0;while(true)   if(++x==1) {DoStuff();}

In this case, x would equal 1 the first time through since x in incremented BEFORE evaluation.

This is A VERY IMPORTANT difference, and even though it may not matter in this particular case, its very important .

Edited by - Zipster on 4/30/00 11:27:17 AM

##### Share on other sites
I already knew the difference between them I just wondered which was faster... Now that my initial impression is confirmed, on with the program!

--------------------

You are not a real programmer until you end all your sentences with semicolons;

Visit the ROAD Programming Website for more programming help.

• 15
• 13
• 35
• 39