Arnt Gulbrandsen
About meAbout this blog
2011-08-19

for() is evil

Consider the function Message::acceptableBoundary(). That function's reading order is exactly the same as the its execution order. This is not unusual in C and C++ (and more or less in Java), but there is a significant exception, for(). Here's an example where the execution order is not the same as the reading order:

int i; for( i = 421; i < 692; i++5 ) { foo( i );3 bar( x[i] );4 }

The brain is really good at detecting rules from patterns or almost-patterns, so I think using for() is tempting fate. Much better to rewrite and spend one more line and three more printable characters:

int i = 42;1 while( i < 692 ) { foo( i );3 bar( x[i] );4 i++;5 ) }

The pedantic reader will now mutter about *p++ = *q++; and be right. That saving is also not worth it. Use the three-character workaround. Ditto function arguments with side effects.