It’s the language, silly

Tuesday, 14 Dec 2004

David Shay complains about a strange looking loop:

It looks like this:

do {
  ...
} while (false);

A loop that runs once. What’s the point of it? Well, the guy used this trick so that he can simulate a GOTO by calling a simple break command. How ugly is that? I advised my colleague to put the body of the loop in a separated method, and call return instead.

Actually, that idiom is not ugly at all, nor is it a GOTO any more than return is, as evidenced by the fact that the suggested transformation to a function is completely formulaic.

What’s ugly is that the language does not offer actual naked blocks as in

{
  // ...
  if( condition ) break;
  // ...
}

so that you have to resort to that silly do { ... } while( 0 ); trick.

Perl does offer naked blocks, and I find myself using them quite a bit. I also find them to be invaluable tools in structuring my code.

Even GOTO isn’t inherently evil. That certainly doesn’t mean I use it much – not once in 500,000 lines of code. It’s just dangerous, not evil. Certain kinds of state machines or parsers f.ex can be much easier to write and read with a few carefully sprinkled GOTOs.