Barr Group FacebookBarr Group TwitterBarr Group LinkedInBarr Group Vimeo

Rules

The following C coding rules relate to the structure of while and for loops:

Rule 8.4.a.) Magic numbers shall not be used as the initial value or in the endpoint test of a while or for loop. (Note that sizeof() is a theoretically handy way to dimension an array but that this method does not work when you pass a pointer to the array instead of the array itself. Thus the most portable method is a constant shared between the array declaration and the loop.)

Rule 8.4.b.) Except for a single loop counter initialization in the first clause of a for statement, assignments shall not be made in any loop’s controlling expression.

Rule 8.4.c.) Infinite loops shall be implemented via the controlling expression for (;;). (Note: We can make no compelling technical argument against while (1), but note that Kernighan & Ritchie have long recommended for (;;) and so many C programmers have become accustomed to structuring their infinite loops this way. In such a case, consistency is all that really matters.)

Rule 8.4.d.) Each loop with an empty body shall feature a set of braces enclosing a comment to explain why nothing needs to be done until after the loop terminates.

Example

// Don’t use a magic number ...
for (int row = 0; row < 100; row++)		  
{
    // ... when you mean a constant.
    for (int col = 0; col < MAX_COL; col++)  
    {
        ...
    }
}

Reasoning

It is always important to synchronize the number of loop iterations to the size of the underlying data structure. Doing this through a single constant prevents a whole class of bugs that can result when changes in one part of the code, such as the dimension of an array, are not matched by changes in other areas of the code, such as a loop iterator that operates on the array. The use of named constants also makes the code easier to read and maintain.

Exceptions

It is acceptable to start or end a loop with an integer value of 0 (considered less magical by most), such as when iterating from or toward the base of an array.

Enforcement

These rules shall be enforced during code reviews.

What’s happening and how it’s done. Get in the know.

Sign up for our newsletter today!

Receive free how-to articles, industry news, and the latest info on Barr Group webinars and training courses via email. 

To prevent automated spam submissions leave this field empty.