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

后端 未结 22 1770
暗喜
暗喜 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

    Yes, there is. The difference is in the return value. The return value of "++i" will be the value after incrementing i. The return of "i++" will be the value before incrementing. This means that code that looks like the following:

    int a = 0;
    int b = ++a; // a is incremented and the result after incrementing is saved to b.
    int c = a++; // a is incremented again and the result before incremening is saved to c.
    

    Therefore, a would be 2, and b and c would each be 1.

    I could rewrite the code like this:

    int a = 0; 
    
    // ++a;
    a = a + 1; // incrementing first.
    b = a; // setting second. 
    
    // a++;
    c = a; // setting first. 
    a = a + 1; // incrementing second. 
    

提交回复
热议问题