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)?
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.
Parallel processing (more cores) and instruction pipelining can make
n++ faster as it is sort of non blocking create a temporary add 1 and reassign.
++i is sort of blocking as it increments inplace, till first inplace operation is complete, you cannot add again. The difference is very minor. And this may not be true all the time (i.e why i said can). If you benchmark you are going to get different results, sometimes ++i win sometime i++ wins. Modern C/C++ compilers are incredibly complex !
And sorry i do not have indepth explaination.
Working with primitives, i++ or ++i hardlly matters. Theoritically ++i should be faster as it doesn't involve creating a temporary but modern compilers can make i++ faster than ++i.
Working with itetators, prefer prefix version over postfix as creation of temporary can be expensive with objects.
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.
Cout<<++i; //prints 3
Cout<<i++; //prints 2
Cout<<i;. //prints 3
This Is what is meant.