Difference between pre-increment and post-increment in a loop?

后端 未结 22 1819
暗喜
暗喜 2020-11-21 23:41

Is there a difference in ++i and i++ in a for loop? Is it simply a syntax thing?

22条回答
  •  我寻月下人不归
    2020-11-22 00:24

    To understand what a FOR loop does

    enter image description here

    The image above shows that FOR can be converted to WHILE, as they eventually have totally the same assembly code (at least in gcc). So we can break down FOR into a couple of pieces, to undertand what it does.

    for (i = 0; i < 5; ++i) {
      DoSomethingA();
      DoSomethingB();
    }
    

    is equal to the WHILE version

    i = 0; //first argument (a statement) of for
    while (i < 5 /*second argument (a condition) of for*/) {
      DoSomethingA();
      DoSomethingB();
      ++i; //third argument (another statement) of for
    }
    

    It means that you can use FOR as a simple version of WHILE:

    1. The first argument of FOR (int i) is executed, outside, before the loop.

    2. The third argument of FOR (i++ or ++i) is executed, inside, in the last line of the loop.

    TL:DR: no matter whether i++ or ++i, we know that when they are standalone, they make no difference but +1 on themselves.

    In school, they usually teach the i++ way, but there are also lots of people prefer the ++i way due to several reasons.

    NOTE: In the past, i++ has very little impact on the performance, as it does not only plus one by itself, but also keeps the original value in the register. But for now, it makes no difference as the compiler makes the plus one part the same.

提交回复
热议问题