Programming Proverbs 12: Leave loop variables alone

Another way of expressing this is to use loop as if they were read-only constants. Loop variables should be initialized and changed only in the loop statement itself. The problem with doing it anywhere else is that it is too easy to either make the modification incorrectly or to do so in the wrong place.

Changing loop variables outside the loop statement also makes programs more difficult to debug and to modify. debugging gets complicated when one has to search for the locations where a variable is modified. Modifications to loop variables should only happen in one place to keep it simple. By treating loop variables as read-only and never modifying them inside the loop the debugging process is simplified at least a little. Sometimes every little bit helps.

A lot of beginners think that once they are done with a program that it will never be revisited. That may be true for programs that are created as class assignments but it is generally not the case for most any other programs. Students should always write their programs as if someone else will later come along to either maintain or enhance it. It's a good habit to get into as it forces better design practices. When it comes to maintaining or more importantly adding code to a loop the last thing you want is problems figuring out where and how the loop control variable is modified.

Keeping it simple (like leaving loop variables alone) is a good idea and a good habit to teach.

This is the twelfth of a series of posts based on the book Programming Proverbs by Henry Ledgard. The index for the series is an earlier post and discussion of the list as a whole is taking place in the comments there. Comments on this "proverb" are of course very welcome here.