goto jumps into loops

Frank Adams franka at mmintl.UUCP
Sat Apr 19 08:10:58 AEST 1986


In article <69 at brl-smoke.ARPA> dmh at mit-borax.ARPA writes:
>
>   Nice timing...Steve Summit's letter about jumping into blocks arrived
>just as I had finished debugging a routine which I actually wrote in Pascal
>and just translated into C for practice.  You guessed it, it jumps into a
>loop, and I honestly don't think there is a way to avoid the goto without
>some VERY ugly code to keep track of the program's state.

It just takes one variable, and isn't ugly at all.

/* Assume the existence of a type named "set", which is intended to simulate
   Further assume the existence of a function
 in(e,l);
 set *l;
 char e;
which returns a boolean 1 iff _e_ is an element of _*l_.
*/
#include <stdio.h>

#include "/usr/dmh/nastydefs"

wrtlist (listp)
set *listp;
	 
/*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.  Notice the absence of any GOTO statements
*/


#define MAX NUM_KEYWORDS   /*The highest element in use by the application*/
#define NONE -1
{
  unsigned char i;
  set list;
  int last = NONE;   /* last is the start of the current string of consecutive
                        members, or -1 if not in such a string */

  /* loop through the possible elements of the set, seeing which are in it */
  for (i = 0; i <= MAX; i += 1) {

    if (in(i, &list)) {
      /* element of set; if not in a sequence, start one */
      if (last = NONE) last = i;
    } else {
      /* not an element; output preceding sequence, if any */
      putrange(last, i-1);
      last = NONE;
    }
  }

  /* output sequence at end of possible range, if any */
  putrange(last, MAX);

  return;
}
/* This routine outputs a sequence of consecutive elements in the set.  There
   are three cases:
    1) the sequence has no elements.  In this case, start will be -1, and
       nothing should be output
    2) the sequence has a single element.  In this case, start will equal
       end, and should be output.
    3) the sequence has more than one element.  In this case, start should be
       output, followed by a dash, then end.
*/
static void putrange(start, end)
  int start, end;
{
  if (start != NONE) {
    printf(" %d", start);
    if (start != end) {
      printf("-%d", end);
    }
  }
  return;
}

There.  That's not only better structured than your program, it's shorter.

Disclaimer: I have not attempted to compile the above program, nor run it
through lint.  It may, therefore, contain errors.

Frank Adams                           ihnp4!philabs!pwa-b!mmintl!franka
Multimate International    52 Oakland Ave North    E. Hartford, CT 06108



More information about the Comp.lang.c mailing list