goto jumps into loops
John P. Nelson
jpn at teddy.UUCP
Sat Apr 19 09:23:36 AEST 1986
>Can any of you
>figure out a way to do this elegantly without the goto?
Wow! That code was UGLY! How about this:
#include "nastydefs"
#define MAX NUM_KEYWORDS
/* This routine should print out a list of the members of List, with adjacent
* members shown contracted as N-M, where N and M are the bounds of a range of
* members.
*/
wrtlist(listp)
register set *listp;
{
register int i;
/* scan entire set */
for (i = 1; i < MAX; ++i) /* note: could just as easily start at 0 */
{
if (in(i, listp))
{
/* this is the start of a run (potential 1 element run) */
printf("%d", i);
/* check for two in a row */
if (++i < MAX && in(i, listp))
{
/* at least two in the run - scan to the end */
for (++i; i < MAX; ++i)
if (!in(i, listp))
break;
printf("-%d", i - 1);
}
}
/* current i is known to NOT be in the set */
}
}
I assumed that the "in" function was expensive - any element is only checked
ONCE. The secret is that the outermost level loop index is modified. A
version with an auxiliary index is also possible, which is possibly slightly
cleaner.
More information about the Comp.lang.c
mailing list