goto a no-go?

Chris wendlec at tcd.ie
Tue Oct 1 06:23:48 PDT 2013


On Tuesday, 1 October 2013 at 11:40:35 UTC, Manu wrote:
> 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.

That was just a made up example (of an obvious case). The real 
case was a bit more complicated (involving an associative array).

> 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.

Sure, but it's good to know that some sub-optimal code is 
optimized, until I find the time to optimize it by hand. 
Optimizing too early can be more harmful than sub-optimal code 
(that is just a wee bit slower but harmless).


More information about the Digitalmars-d mailing list