How we change what others think, feel, believe and do
CHAPTER 8 : Language Usage
8.5 Using 'for'
The for statement in C is effectively a while with initialization and repeated loop statements. Its normal use is where control of the loop requires more than a simple test or comparison.
Comments about while statements are also generally applicable to for statements.
8.5.1 Loop control
A basic use of for is to repeat a loop a given number of times, but how do you count the iterations? If the number of times you want to repeat the loop is in LoopMax, do you count from 0 or 1? There are several possible approaches:
for ( i = 1; i <= LoopMax; i++ ) /* count from 1 to LoopMax */
This may be a valid use, but if you are using it with an array (typically initializing it), then you need to count from zero:
for ( i = 0; i != LoopMax; i++ ) /* count from 0 to LoopMax - 1 */
This would work for accessing an array, but is not defensive, as if 'i' is modified within the loop, (a poor practice!) then 'i' could become greater than LoopMax and the loop would never end. Thus:
for ( i = 0; i < LoopMax; i++ ) /* count from 0 to LoopMax - 1 */
This is the simplest method which can be used in the widest possible set of circumstances. A consistent approach such as this will also help to avoid out-by-one errors.
8.5.2 'while' vs. 'for'
The for loop can be used anywhere a while loop is used, with the first and/or third expression omitted. Thus, for example, it can be used to initialize items used within (but not controlling) the loop.
for ( KeyCount = 0; WordPtr <> (WORD *)NULL; WordLen++, KeyCount++ )
This is more naturally a while loop, as the initialization and repetition have nothing to do with the control of the loop.
KeyCount = 0;
Note that it is not true to say that a for loop can always be replaced by a while, as a continue in the loop would skip the repeated expression:
for ( i = 0; i < WordLen; i++ ) /* difficult to replace with
a 'while' */
It is using the simplicity principle to use a while loop where the control of the loop depends on a simple comparison, and to use a for loop when the control of the loop also needs initialization and/or a repetition of an expression.
8.5.3 Infinite loops
Sometimes an infinitely repeating loop is required, which is escaped with a break or return. Common ways of doing this are for (;;) or while (1). To the uninitiated, however, these are unclear. They can be made more readable with a constant or a simple trailing comment:
while ( TRUE )
for (;;) /* infinite loop */
And the big