- There is
continue;to stop the loop and move to the next loop - There is
break;to stop the loop and move to the end of the loop
Isn’t there some kind of start; that stop the loop and move to the beginning of the loop?
I know it is easy to achieve all of these three actions by just modifying the value of i, but I always try to look for already built-it functions.
No – there is no keyword or other way to do it automatically.
As you already mentioned you can just modify the loop condition variable(s) within your loop. Easy if it’s a simple
icounter, but of course you may have more initialisation to do than just a simple counter.Or you can do something like the following:
The
continue restartLoopwill jump back out to continue with the next iteration of thewhileloop, which then immediately starts theforloop from the beginning including all of the initialisation code. If theforexits normally thebreakstatement after it will break out of the containing while loop.I don’t really recommend doing this in a general sense, but if your loop initialisation process was really complicated it could be worth it because then you wouldn’t need to repeat it all inside the loop. If you needed to do even more initialisation than fits nicely in the
forstatement’s initialisation expression you can easily put it just before theforloop inside thewhileand it will all be re-run…