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

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

    There is no difference if you are not using the value after increment in the loop.

    for (int i = 0; i < 4; ++i){
    cout<

    Both the loops will print 0123.

    But the difference comes when you uses the value after increment/decrement in your loop as below:

    Pre Increment Loop:

    for (int i = 0,k=0; i < 4; k=++i){
    cout<

    Output: 0 0 1 1 2 2 3 3

    Post Increment Loop:

    for (int i = 0, k=0; i < 4; k=i++){
    cout<

    Output: 0 0 1 0 2 1 3 2

    I hope the difference is clear by comparing the output. Point to note here is the increment/decrement is always performed at the end of the for loop and hence the results can be explained.

提交回复
热议问题