On Tuesday, 1 October 2013 at 11:22:12 UTC, Chris wrote:
Just a short question. Usually goto statements are frowned upon as being bad programming style (in textbooks at least). D has it (thankfully) and I've used it, albeit sparingly. Sometimes goto is simply the best and most efficient solution within a code block (to avoid code duplication, unnecessary checks or redirecting to yet another function blah blah). Is it ok or even necessary to use goto in D? Or does the compiler recognize _obvious_ cases and generate code accordingly? For example would it turn something like this

// ...
if (word.length == 1) {
 // format output
 return output;
} else if (word.length > 1) {
  // do some additional processing
  // format output
  return output;
}

into

// ...
if (word.length == 1) goto FormatOutput;

// if word.length > 1, some extra work has to be done
// initialize some variables, parse, do some processing etc.

FormatOutput:
 // .....

return output;

How is that transformation an optimization or improvement? Substituting "return output" for "goto FormatOutput" is not better. So, I assume "// format output" is the code duplication you want to remove? Well, your example should also work like this:

  if (word.length > 1) {
    // do some additional processing
  }
  // format output
  return output;

Regarding goto and D, scope guards [0] are good for removing gotos, because the cleanup-after-error code can be moved.

[0] http://dlang.org/statement.html#ScopeGuardStatement

Reply via email to