goto

Walter Bright newshound1 at digitalmars.com
Thu Feb 5 21:07:13 PST 2009


Andrei Alexandrescu wrote:
> I was coding a simple Euclidean distance function with limit:
> 
> double euclideanDistance(Range)(Range a, Range b, double limit)
> {
>     limit *= limit;
>     double result = 0;
>     for (; !a.empty; a.next, b.next)
>     {
>         enforce(!b.empty);
>         auto t = a.head - b.head;
>         result += t * t;
>         if (result >= limit) goto thatsit;
>     }
>     enforce(b.empty);
>   thatsit:
>     return sqrt(result);
> }
> 
> How would an elegant goto-less approach look like? It should not 
> duplicate code, e.g. the call to sqrt.
> 
> 
> Andrei

double euclideanDistance(Range)(Range a, Range b, double limit)
{
     limit *= limit;
     double result = 0;
     for (; 1; a.next, b.next)
     {
         if (a.empty)
         {
            enforce(b.empty);
            break;
         }
         enforce(!b.empty);
         auto t = a.head - b.head;
         result += t * t;
         if (result >= limit) break;
     }
     return sqrt(result);
}



More information about the Digitalmars-d mailing list