#5. "for" loops should be simple and well-formed

for loops should be well-formed. This means:
  • They should have a single loop counter, which shall be of integral type or an iterator.
  • The loop counter should only be modified in the increment expression of the loop.
  • The loop counter should be incremented or decremented by the same amount at each loop iteration.
  • The loop counter should be accompanied in the loop condition, if anything, by boolean variables.
  • The loop body should be a compound statement, delimited by brackets.
  • The loop body should not contain labels which are the destination of goto statements.
  • The loop body should contain at most one break statement.
  • Use continue with care, preferably in the beginning of the loop body, to exclude certain iterations from the action.
for loop is a practical, readable (once you get used to it) and terse construct, but you need to use it well. Because of its uncommon syntax, using it in a too imaginative way is not a good idea.

All parts of the for loop should be short and readable. Variable names should be chosen to make it easy to understand.

It you follow all the parts of the guideline above, you'll avoid most of the error-prone deviations in for loops. They can be summarized in one: "A for loop should be simple".

When there is complexity regarding the exit condition, or the initialization is not that simple, or the increment expression needs to be something more than just incrementing or decrementing a variable... Then change your loop to a while or a do ... while, which are inherently more readable and less error prone in these more difficult cases.

Bibliography

[McConnell 2004]
Steve McConnell: Code Complete, 2nd Edition, Microsoft Press, 2004.

This book discusses loops in Chapter 16: "Loops" (pages 367-389).

Comments

Popular posts from this blog

#2. Make all type conversions explicit

#13. Organize your code in classes

#7. Always initialize variables