@
@
@YAnri2018-07-04 13:37:35
C++ / C#
@YAnri, 2018-07-04 13:37:35

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;
  }

and
for(int i=1;i<=10;++i)
  {
    cout<<i;
  }

I know what is the difference between "i ++" and "++ i"
But what difference does it make if for will be i ++ or ++ i, it does not change any meaning, so why then some programmers write i ++ in one loop, and in the other ++ i?
I will be very glad if I get an answer to this question :)
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
dom1n1k, 2018-07-04
@dom1n1k

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.

K
Kirill Nesmeyanov, 2018-07-04
@SerafimArts

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.

C
ColdSpirit, 2018-07-04
@ColdSpirit

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! =)

R
Rsa97, 2018-07-04
@Rsa97

In this particular case, there is no difference.

C
codefln, 2018-07-04
@codefln

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 question

Ask a Question

731 491 924 answers to any question