Looping Code Smell?

I read somewhere in the last few days that someone considered that looping over enumerable lists using a for loop should be considered a code smell.  They went on to say that the preferred way to loop should be using the foreach syntax. 

The reasoning behind the the preference was that the for loop syntax opens the possibility for boundary errors.  Everyone has written a loop over an array where we start at 0 and end at array.Length instead of array.Length - 1.

In the past I would not have cared if a developer had used either method of looping.  Today I opened up some code and the first thing that I noticed was that the it used the for syntax and my immediate reaction was to verify the boundary values in the syntax.  So why should I have to do that?  If we're going to write a loop that navigates over an entire collection of data, should we really have to worry about coding the boundaries?  We have the foreach syntax which automatically takes care of the boundaries.  Why not use that?

In the modern development world we go to great lengths to abstract away complexity.  I've come around to believing that the for syntax doesn't achieve this.  Sometimes it may be needed, but for looping over entire collections I think it should be avoided.

Posted By: Donald Belcham

Published at


The Coding Hillbilly
02/15/2007 11:40 AM by
The Coding Hillbilly

I'm with you, Inuit. Have run into problems in recent weeks dealing with an API that doesn't support enumeration but when you can, I always use foreach for everything.

Mack D. Male
02/15/2007 06:00 PM by
Mack D. Male

foreach is quite possibly the best keyword/construct ever created. I find a way to use it.

02/16/2007 02:09 AM by

I think the possibility of a array boundary error is only one part of the reasoning to use foreach. When I conduct code reviews that use for, I find myself verifying every array or collection accessor to ensure they all use the same index. At one point I found a developer had mistakenly switched i and j in a nested for loop. Even though both of these are important arguments in favor of foreach, in my mind the bigger argument is readability and maintainability. I honestly find it easier and less error prone to use

foreach(Book book in books) title = book.Title

than to decipher

for(int i = 0; i < books.Length; i++) title = books[i].Title

There's not much difference between the two conceptually, but a lot more thought and analysis is required to evaluate the for loop.