'goto" gone from computer languages or is it!

Dave Dunfield dave04a at dunfield.com
Mon May 16 16:18:24 CDT 2005


>print_ary (ary, DIM (ary));
>
>void print_ary (int *aryp, int n)
>{
>
>   goto skip_comma;
>   for (;n;aryp++, n--)
>      {
>         printf (", ");
>
>skip_comma:
>          printf ("%u", *aryp);
>      }
>   printf ("\n");
>
>}

>>   I'd skip both the GOTO and the conditional and do it:
>> 
>>         void print_ary(int *aryp,size_t n)
>>         {
>>           size_t  i;
>>           char   *sep;
>> 
>>           assert(aryp != NULL);         /* sorry, gotta check */
>>           assert(n    > 0);
>> 
>>           for (i = 0 , sep = "" ; i < n ; aryp++ , i++)
>>           {
>>             printf("%s%u",sep,&aryp);
>>             sep = ",";
>>           }
>>           putchar('\n');
>>         }

>Clever. I don't like the conditional either, but you are also
>unnecessarily reinitializing sep every time through the loop. With the
>goto I avoid both the conditional and the reinit.

Given that the original example assumes n > 0 (the test is skipped on
first entry to the loop), you can accomplish this function with neither
an extra conditional, superfluous assignment, extra variables or use
of 'goto'

void print_arg(int *aryp, unsigned n)
{
   int i;
   for(i=0; ;) {
      printf("%u", aryp[i]);
      if(++i >= n)
         break;
      fputs(", ", stdout); }
   putc('\n', stdout);
}


-- 
dave04a (at)    Dave Dunfield
dunfield (dot)  Firmware development services & tools: www.dunfield.com
com             Collector of vintage computing equipment:
                http://www.parse.com/~ddunfield/museum/index.html




More information about the cctalk mailing list