goto a no-go?

Manu turkeyman at gmail.com
Tue Oct 1 04:40:26 PDT 2013


On 1 October 2013 21:22, Chris <wendlec at tcd.ie> 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;
>

Well, obviously that should be rewritten:

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

Note: there's an un-handled case in your example, but I'll ignore that.
Anyway, goto is supported. Walter likes it. I use it from time to time.
I'd say 90% of the time I find goto useful is when I need to bail from
nested loops. I've often wondered if something like break(2) would be a
more elegant solution to the breaking out of nested loops problem.

But in direct answer to your question, I think you'll find modern
optimisers are smart enough to make the optimisation you are looking for. I
haven't tested that precise case, but I've definitely expected the
optimiser to do the right thing in similar cases, and it does. I rarely
write code that requires me to have faith in any optimiser though.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20131001/39853c86/attachment-0001.html>


More information about the Digitalmars-d mailing list