Answer the question
In order to leave comments, you need to log in
What's the difference in a for loop between "i++" and "++i"?
Hey,
Can you please tell me what is the difference in the for loop between "i ++" and "++ i"?
e.g.
for(int i=1;i<=10;i++)
{
cout<<i;
}
for(int i=1;i<=10;++i)
{
cout<<i;
}
Answer the question
In order to leave comments, you need to log in
In this case, no assignment is made, so there is no difference in the meaning of the result of the work.
There is a difference in terms of speed (++i works a little faster), but it is so microscopic that it should be safely scored in 99.(9)% of cases. It is even possible that now compilers catch this situation and then the difference disappears altogether.
I myself write ++i, but not for the sake of performance, it's just my historically established taste.
You just need to choose one code style (personal or corporate) and stick to it. Mixing two options within the same program is bad.
As already correctly said - there are no differences in the algorithm. Differences are only in the output code that compilers can generate. They can, simply because this instruction allows for compile-time optimizations. So it all depends on the compiler itself.
I remember from the university, they explained that at the assembler level, ++i turns into one increment instruction, while i++ into two (or one, but not an increment, but a regular add), hence the performance differences. PS This information is not accurate and I can lie, but in general something like this.
As you can see, there is no difference in the output code from gcc 8.1: https://godbolt.org/g/bwa482
You can check it on other versions / compilers - don't forget to share your discoveries! =)
This result is due to the for operation algorithm:
1. Assign i=1
2. Check i <= 10
3. If true, execute the body of the loop, then execute i++
The increase in i++ is performed separately from the condition check (2), the value of i is not used in this case , so there is no difference between i++ and ++i.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question