EDIT : I know how to use for loops / what I can use them for. I’m asking the community your opinions on when certain usages of for loops are good / bad.
Just a general programming question:
Should for loops only be used for iteration?
Note that iteration here is a very vaugly defined term- basically what I mean by it is the traditional for (int i = 0; i < limit; i++) and variants on this.
Ex.:
You should / shouldn’t use for loops for a counter:
for (; keepGoing(); count++) vs while (keepGoing) { count++ }
Some languages may also have certain caveats or different usage patterns too. Without getting too particular, I’m looking at the question from a C++ / C# / Java usage pattern.
Things to consider:
- Ease of coding.
- Readability of code.
- Likelyhood of causing a bug (i.e. are off-by-one errors more common with certain for-loop usage or while loop usage).
You can use a loop also for counters, they are also some kind of iteration.
You should however avoid loops like this:
or
Also try to avoid continue and break statments in the loop, as they make the code hard to read and to debug.