[c++] ++i or i++ in for loops ??

Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?

Is there a reason some programmers write ++i in a normal for loop instead of writing i++?

This question is related to c++ for-loop post-increment pre-increment

The answer is


++i is slightly more efficient due to its semantics:

++i;  // Fetch i, increment it, and return it
i++;  // Fetch i, copy it, increment i, return copy

For int-like indices, the efficiency gain is minimal (if any). For iterators and other heavier-weight objects, avoiding that copy can be a real win (particularly if the loop body doesn't contain much work).

As an example, consider the following loop using a theoretical BigInteger class providing arbitrary precision integers (and thus some sort of vector-like internals):

std::vector<BigInteger> vec;
for (BigInteger i = 0; i < 99999999L; i++) {
  vec.push_back(i);
}

That i++ operation includes copy construction (i.e. operator new, digit-by-digit copy) and destruction (operator delete) for a loop that won't do anything more than essentially make one more copy of the index object. Essentially you've doubled the work to be done (and increased memory fragmentation most likely) by simply using the postfix increment where prefix would have been sufficient.


As others have already noted, pre-increment is usually faster than post-increment for user-defined types. To understand why this is so, look at the typical code pattern to implement both operators:

Foo& operator++()
{
    some_member.increase();
    return *this;
}

Foo operator++(int dummy_parameter_indicating_postfix)
{
    Foo copy(*this);
    ++(*this);
    return copy;
}

As you can see, the prefix version simply modifies the object and returns it by reference.

The postfix version, on the other hand, must make a copy before the actual increment is performed, and then that copy is copied back to the caller by value. It is obvious from the source code that the postfix version must do more work, because it includes a call to the prefix version: ++(*this);

For built-in types, it does not make any difference as long as you discard the value, i.e. as long as you do not embed ++i or i++ in a larger expression such as a = ++i or b = i++.


There is a reason for this: performance. i++ generates a copy, and that's a waste if you immediately discard it. Granted, the compiler can optimize away this copy if i is a primitive, but it can't if it isn't. See this question.


when you use postfix it instantiates on more object in memory. Some people say that it is better to use suffix operator in for loop


No compiler worth its weight in salt will run differently between

for(int i=0; i<10; i++)

and

for(int i=0;i<10;++i)

++i and i++ have the same cost. The only thing that differs is that the return value of ++i is i+1 whereas the return value of i++ is i.

So for those prefering ++i, there's probably no valid justification, just personal preference.

EDIT: This is wrong for classes, as said in about every other post. i++ will generate a copy if i is a class.


With integers, it's preference.

If the loop variable is a class/object, it can make a difference (only profiling can tell you if it's a significant difference), because the post-increment version requires that you create a copy of that object that gets discarded.

If creating that copy is an expensive operation, you're paying that expense once for every time you go through the loop, for no reason at all.

If you get into the habit of always using ++i in for loops, you don't need to stop and think about whether what you're doing in this particular situation makes sense. You just always are.


Personal preference.

Usually. Sometimes it matters but, not to seem like a jerk here, but if you have to ask, it probably doesn't.


++i is a pre-increment; i++ is post-increment.
The downside of post-increment is that it generates an extra value; it returns a copy of the old value while modifying i. Thus, you should avoid it when possible.


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to for-loop

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements?

Examples related to post-increment

Post-increment and Pre-increment concept? ++i or i++ in for loops ?? How do the post increment (i++) and pre increment (++i) operators work in Java? Incrementing in C++ - When to use x++ or ++x? Difference between pre-increment and post-increment in a loop? Is there a performance difference between i++ and ++i in C? C: What is the difference between ++i and i++?

Examples related to pre-increment

Post-increment and Pre-increment concept? ++i or i++ in for loops ?? How do the post increment (i++) and pre increment (++i) operators work in Java? Incrementing in C++ - When to use x++ or ++x? Difference between pre-increment and post-increment in a loop? Is there a performance difference between i++ and ++i in C? C: What is the difference between ++i and i++?