PBP: 067 C-Style Loops

The Best Practices cast the use of C Style For Loops out of our lexicon.  Personally, I don’t get why this is, but haven’t needed them in a while.The PBP says simply, “No, don’t do this.”  Personally, I don’t know why, because I’ve never had a problem with them; I came from C, and that’s how you write for loops.  However, I’ve seen other people who had a less tortured background struggle with them.  They are apparently not clear to some people.

When I’m in a bad mood, I’ll tell them to learn the darn language they’re using, and get over it.  Then I realize that’s the equivalent of “Get off my lawn!” and I try to reel myself back in.

One thing that is true about the C style of for loop is that it can almost always be written as a while loop instead if you actually need what it does.  While I like having the after-condition in the for instead of in the body where it could be missed (hello, infinite loop!) it isn’t critical and the same loop written as a while is clearer to a lot of people.

Perl also provides a handy other loop to do counting and array iteration, which handles a lot of the cases you’d use the for loop for, anyway.

I generally don’t use the C form any more, but I do occasionally think, “It would be perfect here!”

2 Responses to “PBP: 067 C-Style Loops”

  1. choroba says:

    The reason why you shouldn’t is C-style loops are prone to off-by-one errors. On the other hand, they tend to be the fastest, so one has to resort to them in time critical parts of code.

  2. Last I knew, C-style for loops are actually the slowest in Perl, because the post-condition implicitly becomes a continue {} block. Is the penalty for that continue {} block now gone?

    Of the others I am not sure which is faster, a while that increments a counter is faster than a foreach over a range, but I wouldn’t be surprised if it’s the latter. At the very least, a foreach over a range is specially handled to not actually have to create a list to iterative over, so the difference is not going to be huge.

    However, yes, the reason to not use C-style for loops (or the equivalent while form, either) is indeed that they are prone to off-by-one errors. It’s much harder to mess up a range in the same way as a comparison.

Leave a Reply to Aristotle Pagaltzis