I have a for loop that searches an array of structures in order to find a specific structure.
Now this array may be of size 10000.
Inside the for loop I might gather some extra information that will tell me where exactly is the structure you are looking for. So if your index is currently ‘5’, you might find out that it’s not in ‘5’ but in ‘9000’.
So I use this information in order to change the index.
Now the code works perfectly fine without changing the index in the sense that it does find the information needed. However if I’m 100% sure that what I’m doing is correct in this case, is it OK to change the index in the for loop in order to get results faster?
Thanks in advance
It’s absolutely fine. The language doesn’t distinguish between changing the index in the loop body and changing it in the increment statement within the loop header.
is mostly equivalent to
One difference is that a
continuestatement within the loop body of aforloop will still execute theincrement-statement, which could cause problems if you’re not expecting it.Also be careful that you don’t create an infinite loop by overrunning your terminating condition.