Listing 1: Better nested for loops

#define MAXNUMLOOPS 10
void forfun (int *, int *, int);
void work(int *, int)
int checkcount;
   
main()
{
  int startval[MAXNUMLOOPS], endval[MAXNUMLOOPS];
  int numloops;
   
  numloops = 3;
  startval[0] = 1, startval[1] = 1,
  startval[2] = 1;
  endval[0] = 200, endval[1] = 200,
  endval[2] = 200;
  forfun (startval, endval, numloops);
  exit (0);
}
   
void work(int *r, int numloops)
{
  ++checkcount;
}
   
void forfun(int *startval, int *endval,
           int numloops)
{
  int *curvals, i;
  register int *curlevel, lastval, level;
   
  // Allocate temporary counter array
  curvals = (int *)malloc(numloops *
    sizeof(int *));
   
  for (i = 0; i < numloops; ++i)
    curvals[i] = startval[i];
  
  for(;;) {
    // Perform inner loop
    level = numloops - 1;
    curlevel = curvals + level;
    for (lastval = endval[level];
       *curlevel <= lastval;
       ++*curlevel) {
      work(curvals, numloops);
    }
  
    // Reset counter, and inc outer loop(s)
    do {
      *curlevel = startval[level];
   
      // Bump back a level and increment counter
      --curlevel;
      if (--level < 0) {
        free(curvals);
        return;     // Done processing
      }
    } while (++*curlevel > endval[level]);
  }
  // NO EXIT HERE
}
/* End of File */