21 September 2007

Why for(;;)-loops are bad


I am talking about the C programming language here, World's most portable assembling language. I don't object against for-loops that are different from C's (e.g. when you can write "for (i in collection) ...").

My point is simple. Consider the general form of the for(;;)-loop:

The semantics of that construct is:
INIT ; while(not COND) {BODY; DELTA}

Please note, that the last part is not {DELTA; BODY}. Or is it? Are you sure, you will always remember that well? Which one it is.

Why should I bother to remember a construct with four parts, when the construct with three parts (namely the equivalent "while" loop) will always work?

Of course, the for(;;)-loop is a nice idiom when doing mundane loops over data structures or simple counting from 1 to n. Or was it from 0 to n? Or to n-1? When doing it with "while" the one-off's are always easier to spot, because the semantics is very clear (invariants help).
If you really want an idiom, encapsulate the loop in the data structure module (ADT, class, ...). That's what functional and OO languages are good at. But when doing assembly-programming we better mind our fence-posts.


Post a Comment