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

后端 未结 22 1735
暗喜
暗喜 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:13

    There can be a difference for loops. This is the practical application of post/pre-increment.

            int i = 0;
            while(i++ <= 10) {
                Console.Write(i);
            }
            Console.Write(System.Environment.NewLine);
    
            i = 0;
            while(++i <= 10) {
                Console.Write(i);
            }
            Console.ReadLine();
    

    While the first one counts to 11 and loops 11 times, the second does not.

    Mostly this is rather used in a simple while(x-- > 0 ) ; - - Loop to iterate for example all elements of an array (exempting foreach-constructs here).

提交回复
热议问题