+ 26
Which is better in a loop: post-increment (i++) or pre-increment (++i).
Since the post-increment (i++) operator has to return the original value of i, and not the incremented value i + 1, it has to store the old version of i. This means that it typically needlessly uses additional memory to store that value, since, in most cases, we do not actually use the old version of i, and it is simply discarded. While pre-increment (++i), we do not have to save the old value of i — we can simply add to it and return. This aligns much better with the typical use-case in a for-loop, since we rarely need the old value of i in that context. My question is: when making a for-loop is it good practice to use a post-increment (i++) or pre-increment (++i)?
41 Réponses
+ 20
Surprisingly ++i is better than i++ since it's faster on the cpu. Here's the explanation:
i++ does{
temp = i;
i=i+1;
return temp;
}
while ++i only does {
i = i+1;
return i;
}
+ 14
Aymane Boukrouh [Inactive] I often use the post-increment, which is also the most commonly use. I want opinion of other programmers as to which method is better so as to adopt.
+ 12
I always write ++i, except when I specifically need the trait of i++ to change the value after the statement.
From what I've heard, compiler optimizes i++ away anyway when possible, but I haven't really looked into compiled code.
+ 8
~ swim ~
what is the difference in modern pc to execute i++ faster?
+ 8
thanks ~ swim ~
+ 7
The thing is that, you should be able to use them where they ought to be.... If you solely need to increment, you can use any of them. (i.e., pre/post)
+ 7
Neither are best, you use the most appropriate one according to the needs of your code. ☺
+ 7
Isn't it somewhat strange that the most overasked questions are also the most overanswered ones?
+ 6
Guillem Domènech
I think you did mean
return temp
+ 5
Post increment(i++) is better in case where we want i value increased in next step not in current step where as pre increment is good when we required instant increment in value of i that is in current step only.
int i=2;
Cout<<++i; //prints 3
Cout<<i++; //prints 2
Cout<<i;. //prints 3
This Is what is meant.
+ 5
It is subjective - depending on the scenario.....
+ 4
Meny Evolving I agree
+ 4
++i
+ 4
Both are good, the choice is up to you.
+ 4
HonFu Completely agree with you, it's after all just i++ and ++i.
+ 3
++i
+ 3
I personally like prefix
+ 3
With my little knowledge I was taught of
i++
The other one I have come to learn here.
Learning well here
+ 3
Both are good at their place but pre-increment is good