Search code examples
loopsfor-loopincrementdecrement

increment and decrements in for loop


In a for loop should I use only i++ or i-- operators ? OR can I also use i+10, i+20,i-20 ? I used i+10 in the increment place in the For loop , it is not getting executed.but when I use i++ , it is getting executed.so please help me solve this ! I tried for(i=0;i<=100;i+20) is it wrong ?


Solution

  • In C and C++ at least, the statement:

    i + 20
    

    is an expression statement - the expression is evaluated (or may not be if the optimiser figures out the result does not affect the observable behaviour of the program, which is likely) but otherwise ignored. In fact, the statement:

    42
    

    is also valid but equally useless.


    What you should be doing is one of:

    i += 20
    i = i + 20
    

    That will work better in your loop because it actually modifies the loop control variable.